C# Page Fields not populating as expected

80 views Asked by At

Could someone please tell me what I am doing wrong? I am trying to call the method automatically when the page loads, however, it does not work.

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        customerInformation();

    }
}

protected void ddNames_SelectedIndexChanged(object sender, EventArgs e)
{
    customerInformation();
}

private void customerInformation()
{
    string dbString = ConfigurationManager.ConnectionStrings["TechSupportDBConString"].ConnectionString;
    string query = "SELECT * FROM Customers WHERE Name='" + ddNames.Text + "'";

    SqlConnection Connection = new SqlConnection(dbString);
    Connection.Open();

    SqlCommand Com = new SqlCommand(query, Connection);
    SqlDataReader reader = Com.ExecuteReader();
    if (reader.Read())
    {
        lblName.Text = reader["Name"].ToString() + "'s Personal Information";
        lblAddress.Text = reader["Address"].ToString() + "\n" + reader["City"].ToString() + " " + reader["State"].ToString() + " " + reader["ZipCode"].ToString();
        lblPhone.Text = reader["Phone"].ToString();
        lblEmail.Text = reader["Email"].ToString();

        reader.Close();
        Connection.Close();
    }
}
1

There are 1 answers

3
Navoneel Talukdar On

Ok looking through your code I can see the connection of reader and database is closed in loop itself which should not be done.

SqlDataReader reader = command.ExecuteReader();    
if (reader.HasRows)
{
     while (reader.Read())
     {
                //populate fields from reader
     }
}
else
{
     lbl.Text = "No records found.";
}
reader.Close();
Connection.Close();

Next thing which I noticed that dropdown selected text/value should be either ddNames.SelectedItem.Text or in case of value passing ddNames.SelectedValue.

Next thing make sure that each reader name should exactly match with table column name.

Last but not least always do a proper null check before applying ToString().if any column has null value ToString() would fail to convert.

Hope this helps.