Click here to Skip to main content
14,423,188 members
Rate this:
Please Sign up or sign in to vote.
See more:
I want to retrieve an email address from the database , strore it in a variable of string type and then send mail on that email address,the email address is successfully rerieved but ehen i write this variable in send mail method it shows error "use of unassigned local variable", the code is shown below.

con.Open();
        string addquery = "SELECT  [EMAIL] FROM [DATABASE NAME].[dbo].[TABLE NAME] where Column Name='" + txtRegEmp.Text + "'";
        //string query = "select EMAIL from USER where REGNO_EMPID = '" + txtRRegEmp.Text + "'";
        SqlCommand sqlcom = new SqlCommand(addquery, con);
        SqlDataReader myreader;
        String emailad;
        myreader = sqlcom.ExecuteReader();
        while (myreader.Read())
        {
            emailad = myreader[0].ToString();
           
        }
        myreader.Close();
        con.Close();
        //sending email button code 
       Response.Write(SendMail("abc@gmail.com", "emailad", "abc@gmail.com", "Good work done"));


it shows error of emailad

please guide me in this regard
Posted
Updated 11-May-11 14:07pm
v2
Comments
muntahach 11-May-11 18:24pm
   
it shows error when execute scalar is used
Cannot implicitly convert type 'string' to 'System.Data.SqlClient.SqlDataReader'
raju melveetilpurayil 11-May-11 19:08pm
   
[Edit] edited for more readability [/Edit]
Rate this:
Please Sign up or sign in to vote.

Solution 2

If you want to select single value from Database you can use ExecuteScalar() Command
ExecuteScalar() from MSDN[^]

check the sample
SqlConnection con = new SqlConnection("yourConnectionString");
            string sqlcomd = string.Format("SELECT  email FROM  table WHERE  userid ='{0}'", "65");
            con.Open();
            SqlCommand cmd = new SqlCommand(sqlcomd, con);
            string emailId = string.Empty;
            try
            {
                emailId = Convert.ToString(cmd.ExecuteScalar());
            }
            finally
            {
                con.Close();
            }
   
Rate this:
Please Sign up or sign in to vote.

Solution 1

don't ever try any SqlReader to extract just one value...
use this:
SqlCommand sqlcom = new SqlCommand(addquery, con);

 String emailad;
 emailad = (string)sqlcom.ExecuteScalar( );
SendMail(.., emailad, ..);


Check out your method SendMail espicially on your quotes around "emailad"
don't use quites
   
v2
Comments
muntahach 11-May-11 18:24pm
   
it shows error when execute scalar is used
Cannot implicitly convert type 'string' to 'System.Data.SqlClient.SqlDataReader'

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100