【问题标题】:Showing only Last Selected Item from CheckBoxList仅显示 CheckBoxList 中最后选择的项目
【发布时间】:2015-06-29 22:11:03
【问题描述】:

我正在尝试对 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 中显示选中。我做错了什么?

【问题讨论】:

  • 如果员工有多个城市,如何存储在数据库中?换句话说,当员工拥有多个城市时,sdr["CityID"].ToString() 的输出是什么?

标签: c# asp.net data-binding checkboxlist


【解决方案1】:

我认为是因为您将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;
        }
    }
}

【讨论】:

    猜你喜欢
    • 2011-12-02
    • 1970-01-01
    • 1970-01-01
    • 2013-07-29
    • 1970-01-01
    • 1970-01-01
    • 2016-10-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多