First I want to thank you for the help and I am somewhat new at C# so forgive me if I have something listed wrong. This is what I got:
I am working on a school project designing a car dealership website. I have an inventory list that allows you to edit any car in the inventory. When you click on the edit button it takes you to the edit page and populates the controls with selections from the database. I have an options table that stores the VehicleID and Option ID. When the page loads it fills all the DropDownLists for the vehicle info with the data and selects the correct item according to the database selection but the CheckBoxList does not select the items that are on the Options table. I checked the query in SSMS and it returns the correct data. I have stepped through the method and it works till the “(currentCheckBox != null) if statement. It doesn’t throw any errors but it also doesn’t select items when the page renders.
I thought it might have been something with the page life cycle since databound controls don’t render until the end but the DropDown’s I have fill and selects the correct item according to the database.
Can anyone shed some light?? Thanks again
protected void Page_Load(object sender, EventArgs e)
{
//R Check to see if the page is PostBack
if (IsPostBack == false)
{
lblCurrVehicleID.Text = Request.QueryString["ID"].ToString();
//capture the customer ID from the query string for edit
int VehicleID = int.Parse(Request.QueryString["ID"]);
LoadVehicleData(VehicleID);
LoadVehicleOptions(VehicleID);
}
}
protected void LoadVehicleOptions(int ID)
{
//Get vehicle ID
int VehicleID = ID;
//Declare the connection object
SqlConnection Conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DealershipData"].ConnectionString);
//Define you query
string sql = "SELECT * FROM VehicleOptions WHERE InventoryID=@VehicleID";
//Declare the Command
SqlCommand cmd = new SqlCommand(sql, Conn);
try
{
//Make the connection
Conn.Open();
//Add the parameters needed for the SQL query
cmd.Parameters.AddWithValue("@VehicleID", VehicleID);
//Declare the DataReader
SqlDataReader dr = null;
//Fill the DataReader
dr = cmd.ExecuteReader();
//Get the data
if (dr.Read() == false)
{
//No Records
dr.Close();
Conn.Close();
lblOptError.Text = "No record found";
return;
}
//CheckBoxList chkbx = (CheckBoxList)Form.FindControl("cblOptions");
while (dr.Read())
{
//ListItem currentCheckBox = chkbx.Items.FindByValue(dr["OptionID"].ToString());
ListItem currentCheckBox = default(ListItem);
currentCheckBox = cblOptions.Items.FindByValue(dr["OptionID"].ToString());
if (currentCheckBox != null) Problem happens here {
currentCheckBox.Selected = true;
}
}
//Close the data reader and database connection
dr.Close();
Conn.Close();
}
catch (Exception ex)
{
lblOptError.Text = ex.Message;
}
}