Getting CheckBoxList Item values

2019-02-16 16:38发布

I have a CheckBoxList which I'm populating with data. When I attempt to retrieve the checked items from the list I can only grab the item ordinal, I cannot get the value.

I've read that you can use Items[i].Value however when I try to do this I get an error stating that there is no extension method 'value'.

Here's the code I'm using to try and grab the information (note the GetItemText(i) actually only gives me the item position, not the text for the item)

   private void btnGO_Click(object sender, EventArgs e)
{
    for (int i = 0; i < chBoxListTables.Items.Count; i++)
    {
        if (chBoxListTables.GetItemChecked(i))
        {
            string str = chBoxListTables.GetItemText(i);
            MessageBox.Show(str);

            //next line invalid extension method
            chBoxListTables.Items[i].value;
        }
    }
}

This is using .Net 4.0

Any thoughts would be appreciated...thanks

8条回答
走好不送
2楼-- · 2019-02-16 17:08

Try to use this :

 private void button1_Click(object sender, EventArgs e)
    {

        for (int i = 0; i < chBoxListTables.Items.Count; i++)
            if (chBoxListTables.GetItemCheckState(i) == CheckState.Checked)
            {
               txtBx.text += chBoxListTables.Items[i].ToString() + " \n"; 

            }
    }
查看更多
闹够了就滚
3楼-- · 2019-02-16 17:13

Try to use this.

        for (int i = 0; i < chBoxListTables.Items.Count; i++)
        {
            if (chBoxListTables.Items[i].Selected)
            {
                string str = chBoxListTables.Items[i].Text;
                MessageBox.Show(str);

                var itemValue = chBoxListTables.Items[i].Value;
            }
        }

The "V" should be in CAPS in Value.

Here is another code example used in WinForm app and runs properly.

        var chBoxList= new CheckedListBox();
        chBoxList.Items.Add(new ListItem("One", "1"));
        chBoxList.Items.Add(new ListItem("Two", "2"));
        chBoxList.SetItemChecked(1, true);

        var checkedItems = chBoxList.CheckedItems;
        var chkText = ((ListItem)checkedItems[0]).Text;
        var chkValue = ((ListItem)checkedItems[0]).Value;
        MessageBox.Show(chkText);
        MessageBox.Show(chkValue);
查看更多
登录 后发表回答