selecting checkbox from checkbox list on condition
i have 5 checkboxlists, and each of the checkboxlists have the same 6 checkboxes.
i have to check these checkboxlists during page_Load
under certain conditions.
How do i do that.?
for (int j = 0; j < no_of_listitem; j++)
{
SqlCommand check = new SqlCommand("SELECT ISGoal1, ISGoal2,ISGoal3, ISGoal4,ISGoal5 FROM PRM2011_EMPLOYEE_GOAL WHERE EmployeeID = '" + employeeid[j] + "'", con);
SqlDataReader y = check.ExecuteReader();
while (y.Read())
{
if (null != y && y.HasRows)
{
string yes_or_no = y["ISGoal1"].ToString();
yes_or_no = yes_or_no.Trim();
if (yes_or_no == "Yes")
{
CheckBoxList1.Items[j].Selected = true;
}
//else CheckBoxList1.Items[j].Selected = false;
y开发者_高级运维es_or_no = y["ISGoal2"].ToString();
yes_or_no = yes_or_no.Trim();
if (yes_or_no == "Yes")
{
CheckBoxList2.Items[j].Selected = true;
}
//else CheckBoxList2.Items[j].Selected = false;
yes_or_no = y["ISGoal3"].ToString();
yes_or_no = yes_or_no.Trim();
if (yes_or_no == "Yes")
{
CheckBoxList3.Items[j].Selected = true;
}
//else CheckBoxList3.Items[j].Selected = false;
yes_or_no = y["ISGoal4"].ToString();
yes_or_no = yes_or_no.Trim();
if (yes_or_no == "Yes")
{
CheckBoxList4.Items[j].Selected = true;
}
//else CheckBoxList4.Items[j].Selected = false;
yes_or_no = y["ISGoal5"].ToString();
yes_or_no = yes_or_no.Trim();
if (yes_or_no == "Yes")
{
CheckBoxList5.Items[j].Selected = true;
}
//else CheckBoxList5.Items[j].Selected = false;
}
}
y.Close();
}
employeeid[]
contains id of 6 employees.no_of_listitems is 6 which is the list of thses 6 employee ids.
Create a list with your CheckBoxList in it. Then, replace the code with something like this:
for(int z = 1; z <= checkboxLists.Count; z++)
{
checkboxLists[z].Items[j].Selected = y["ISGoal" + z].ToString().Trim() == "yes";
}
Keep in mind though that this code is not type-safe. Normally, you'd want to avoid using string in your code and y["ISGoal"+z] might be null. If it is, the application will crash. This mean you want to make checks to make sure it's ok. Trying to make a ToString() or Trim() on null will make a NullPointerException. You might also want to change "yes" by bit in your database. It would be much more safe to work with. What if someone writes "true" instead of yes?
I hope it helps out. If you have any question, don't hesitate.
精彩评论