为什么我无法获得某个项目的具体价值?
List<int> IdFundosSelecionados = new List<int>();
for(int i = 0; i < checkedListBox1.Items.Count; i++)
{
if(checkedListBox1.GetItemCheckState(i) == CheckState.Checked)
{
IdFundosSelecionados.Add(checkedListBox1.Items[i].value) //it isn't working
}
}
OBS:我想得到的CHECKED值不是选中的(它与question不同)
答案 0 :(得分:1)
这将解决您的问题:
for(int i = 0; i < checkedListBox1.Items.Count; i++)
{
if(checkedListBox1.GetItemCheckState(i) == CheckState.Checked)
{
IdFundosSelecionados.Add(((int)checkedListBox1.Items[i]))
}
}
你试过这个吗?
List<int> IdFundosSelecionados = new List<int>();
for(int i = 0; i < checkedListBox1.Items.Count; i++)
{
if(checkedListBox1.GetItemCheckState(i) == CheckState.Checked)
{
IdFundosSelecionados.Add(checkedListBox1.Items[i].text)
}
}
我最喜欢的一个是(个人意见):
List<int> IdFundosSelecionados = new List<int>();
foreach (ListItem li1 in checkedListBox1.CheckedItems)
{
if (li1.Selected == true)
{
IdFundosSelecionados.Add(li1.Text)
}
}
答案 1 :(得分:0)
这取决于您如何将项目添加到CheckedListBox,但您只需将项目转换为您添加它们的任何对象类型。一旦你有原始类型,你可以将它转换为int,但你需要(因为IdFundosSelecionades是List)。
例如......
public Form1()
{
InitializeComponent();
for (int i = 1; i < 15; i++)
checkedListBox1.Items.Add(i);
}
private void button1_Click(object sender, EventArgs e)
{
for (int i = 0; i < checkedListBox1.Items.Count; i++)
{
if (checkedListBox1.GetItemCheckState(i) == CheckState.Checked)
IdFundosSelecionades.Add((int)checkedListBox1.Items[i]);
// added as int, so cast as int
}
}