仅显示 CheckBoxList 中最后选择的项目
Showing only Last Selected Item from CheckBoxList
我正在尝试对 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 中只会显示最后一个城市。我做错了什么?
我认为是因为您将 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;
}
}
}
我正在尝试对 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 中只会显示最后一个城市。我做错了什么?
我认为是因为您将 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;
}
}
}