Click here to Skip to main content
15,920,602 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
I have written the code to get my drop-down list selection to print a piece of information into my text box from the database. There are no errors highlighted by visual studio in the code, and it appears correct to me but nothing goes into the text box once a selection is made in the drop-down list.

C#
protected void perBanDDL_SelectedIndexChanged(object sender, EventArgs e)
        {
            //Creating a Select statement that searches for record that matches PersonalID from Value property.
            string perBanSelectSql;
            perBanSelectSql = "SELECT PersonalEmail FROM Personal WHERE PersonalID='" + perBanDDL.SelectedItem.Value + "'";

            //defining ADO.NET objects.
            SqlConnection conE1 = new SqlConnection(adminCon);
            SqlCommand cmdE1 = new SqlCommand(perBanSelectSql, conE1);
            SqlDataReader readerE1;


            try
            {
                conE1.Open();
                readerE1 = cmdE1.ExecuteReader();
                readerE1.Read();

                //Filling text box with email

                banEmailTB.Text = readerE1["PersonalEmail"].ToString();

                readerE1.Close();

                //Cannot find the problem in this method, but does not print email into textbox. No errors in Error list.

            }
            catch (Exception err)
            {
                perBanTxtLabel.Text = "Error getting Email";
                perBanTxtLabel.Text += err.Message;
            }
            finally
            {
                conE1.Close();
            }

        }
Posted
Updated 22-Apr-14 23:44pm
v2
Comments
Herman<T>.Instance 23-Apr-14 5:45am    
while (readerE1.Read())
DamithSL 23-Apr-14 5:56am    
what is the column type of PersonalID?
Coder-Ferg 23-Apr-14 14:03pm    
The column type is varchar(7)

If your query returning only one row it is better to use ExecuteScalar() than Executereader()

Try With Folowing code
C#
SqlConnection conE1 = new SqlConnection(adminCon);
SqlCommand cmdE1 = new SqlCommand(perBanSelectSql, conE1);

try
{
conE1.Open();
banEmailTB.Text=cmdE1.ExecuteScalar().ToString();
}
catch (Exception err)
{
perBanTxtLabel.Text = "Error getting Email";
perBanTxtLabel.Text += err.Message;
}
finally
{
conE1.Close();
}
 
Share this answer
 
Comments
Coder-Ferg 23-Apr-14 6:03am    
Perfect! Thank you, worked for me.
int id = Convert.ToInt32(perBanDDL.SelectedItem.Value);<br />
string perBanSelectSql="SELECT PersonalEmail FROM Personal WHERE PersonalID=@PersonalID";<br />
SqlCommand cmdE1 = new SqlCommand(perBanSelectSql, conE1);    cmdE1.Parameters.AddWithValue("@PersonalID", id);
 
Share this answer
 

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