Click here to Skip to main content
15,892,809 members
Please Sign up or sign in to vote.
2.33/5 (3 votes)
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 13: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]

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();
            }
 
Share this answer
 
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
 
Share this answer
 
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, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900