c# – CheckBoxList ListItem在动态添加数据后总是为0

前端之家收集整理的这篇文章主要介绍了c# – CheckBoxList ListItem在动态添加数据后总是为0前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在aspx代码中有以下代码.我想将ListItem复选框添加到ColumnsList,并在按钮上单击查找所有已检查的对象.

但是当我尝试获取所选项目按钮时,列列表计数将变为0.

<asp:checkBoxlist runat="server" EnableViewState="true" id="ColumnsList"/>

在后面的代码中,我将数据添加到我的ColumnsList中,如下所示

public override void OnLoad()
{
    if(!this.IsPostBack)
    {
       this.ColumnsList.Items.Add(new ListItem { Text= "Text1",Value = "value1"    });
       this.ColumnsList.Items.Add(new ListItem { Text= "Text2",Value = "value2"  });
    }
}

//这是按钮点击监听器

private void Button_Click(object sender,EventArgs eventArgs)
{
    // Count is 0 instead of 2
    var count = this.ColumnsList.Items.Count;
    foreach(ListItem item in this.ColumnsList.Items)
    {
        var selected = item.Selected;
        // add selected to a list..etc

    }
}

注意:应用程序在Sharepoint 2010中部署.

解决方法

我试图模拟你正在尝试的,这里是一步一步的解决方案.

Step 1: Instead of creating override OnLoad() method,you can use
Page_Load() method to add items to your ComboBoxList control,like
below. Don’t forget to put a comma between Text and Value property while creating a new ListItem.

protected void Page_Load(object sender,EventArgs e)
{
    if(!this.IsPostBack)
    {
        this.ColumnsList.Items.Add(new ListItem { Text= "Text1",Value = "value1" });
        this.ColumnsList.Items.Add(new ListItem { Text = "Text2",Value = "value2" }); 
        this.ColumnsList.Items.Add(new ListItem { Text = "Text3",Value = "value3" });
        this.ColumnsList.Items.Add(new ListItem { Text = "Text4",Value = "value4" });
    }
}

Step 2: After this,I created a button click event like yours,but
wrote only single line there to get the count of selected items as
shown below.

protected void Button1_Click(object sender,EventArgs e)
{
    var count = this.ColumnsList.Items.Cast<ListItem>().Count(li => li.Selected);
}

注意:检查您的按钮点击事件. this.ColumnsList.Items.Count将返回您在ComboBoxList和item.Selected中的项目的计数.从循环中可以看到该项目是否被选择.但是,选择的var将会为您提供最后一个项目的状态,因为您将覆盖每个项目的值.

原文链接:/csharp/92507.html

猜你在找的C#相关文章