On my site I have a drop down menu that is used to select the value for a WHERE clause in my SQL statment. The user picks a name from the drop down menu which activates the SQL statement and selects the corresponding record from the database and populates text fields below with the corresponding data. The problem I'm running into is that the first item in the drop down menu is an entry that says "SELECT EMPLOYEE" if a user selects this after selecting an employee name I want the text fields to clear out the value. I got this to work using an if else statement but don't understand why. Can someone please explain the use of:
if (reader.Read())
to me in the following context.
Also I tried to use
if(!read.Read())
but this didn't work. Why not?
Thanks
protected void employeeList_SelectedIndexChanged(object sender, EventArgs e)
{
{
SqlConnection conn;
SqlCommand comm;
SqlDataReader reader;
string connectionString = ConfigurationManager.ConnectionStrings["Dorknozzle"].ConnectionString;
conn = new SqlConnection(connectionString);
comm = new SqlCommand("SELECT Name, EmployeeID, DepartmentID, Username, Password, Address, City, State, Zip, HomePhone, Extension, MobilePhone FROM Employees WHERE EmployeeID = @EmployeeID", conn);
comm.Parameters.Add("@EmployeeID", System.Data.SqlDbType.Int);
comm.Parameters["@EmployeeID"].Value = employeeList.SelectedItem.Value;
try
{
conn.Open();
reader = comm.ExecuteReader();
if (reader.Read())
{
nameTextBox.Text = reader["Name"].ToString();
userNameTextBox.Text = reader["Username"].ToString();
addressTextBox.Text = reader["Address"].ToString();
cityTextBox.Text = reader["City"].ToString();
stateTextBox.Text = reader["State"].ToString();
zipTextBox.Text = reader["Zip"].ToString();
homePhoneTextBox.Text = reader["HomePhone"].ToString();
extensionTextBox.Text = reader["Extension"].ToString();
mobilePhoneTextBox.Text = reader["MobilePhone"].ToString();
}
else <<<<<<<<<<<<<<<<<<<here i tried if(!reader.Read()) but it didn't work
{
nameTextBox.Text = "";
userNameTextBox.Text = "";
addressTextBox.Text = "";
cityTextBox.Text = "";
stateTextBox.Text = "";
zipTextBox.Text = "";
homePhoneTextBox.Text = "";
extensionTextBox.Text = "";
mobilePhoneTextBox.Text = "";
}
reader.Close();
updateButton.Enabled = true;
deleteButton.Enabled = true;
}
catch
{
dbErrorLabel.Text =
"Error loading the employee details!<br />";
}
finally
{
conn.Close();
}
}
}