我试图对CheckBoxList进行数据绑定,但只选择了最后一项。
ASPX:
<asp:CheckBoxList ID="CityCheckBoxList" runat="server"
DataSourceID="SqlDS1" DataTextField="City"
DataValueField="CityID" AutoPostBack="True">
</asp:CheckBoxList>
<asp:SqlDataSource ID="SqlDS1" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommandType="StoredProcedure">
</asp:SqlDataSource>
代码背后:
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
EmployeeIdTextBox.Text = sdr["EmployeeID"].ToString();
EmployeeNameTextBox.Text = sdr["EmployeeName"].ToString();
CityCheckBoxList.DataBind();
ListItem currentCheckBox = CityCheckBoxList.Items.FindByValue(sdr["CityID"].ToString());
if (currentCheckBox != null)
{
currentCheckBox.Selected = true;
}
}
}
如果员工属于多个城市,则只会在CityCheckBoxList中显示最后一个城市。我做错了什么?
答案 0 :(得分:0)
我认为因为你对数据库中的每个员工都绑定了CityCheckBoxList
。复选框的数据绑定应移到循环外部。试试这个:
using (SqlDataReader sdr = cmd.ExecuteReader())
{
CityCheckBoxList.DataBind();
while (sdr.Read())
{
EmployeeIdTextBox.Text = sdr["EmployeeID"].ToString();
EmployeeNameTextBox.Text = sdr["EmployeeName"].ToString();
ListItem currentCheckBox = CityCheckBoxList.Items.FindByValue(sdr["CityID"].ToString());
if (currentCheckBox != null)
{
currentCheckBox.Selected = true;
}
}
}