我在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 yourComboBoxList
control,like
below. Don’t forget to put acomma
betweenText
andValue
property while creating a newListItem
.
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将会为您提供最后一个项目的状态,因为您将覆盖每个项目的值.