1. 程式人生 > >1、checklistbox 用法總結 http://blog.sina.com.cn/s/blog_4cf58c9c010106mx.html

1、checklistbox 用法總結 http://blog.sina.com.cn/s/blog_4cf58c9c010106mx.html

最近用到checklistbox控制元件,在使用其過程中,花了較多的時間,這裡我收集了其相關的程式碼段,希望對大家有所幫助。
1.
新增項
checkedListBox1.Items.Add("藍色");
checkedListBox1.Items.Add("紅色");
checkedListBox1.Items.Add("黃色");

2.
判斷第i項是否選中,選中為true,否則為false
if(checkedListBox1.GetItemChecked(i))
{
return true;
}
else
{
return false;
}

3.
設定第i項是否選中
checkedListBox1.SetItemChecked(i, true); //true改為false為沒有選中。
4.
設定全選
新增一個名為select_all的checkbox控制元件,由其控制checkedListBox是全選還是全不選。
private
void select_all_CheckedChanged(object sender, EventArgs e)
{
if(select_all.Checked)
{
for (int j = 0; j < checkedListBox1.Items.Count; j++)
checkedListBox1.SetItemChecked(j, true);
}
else
{
for (int j =0; j < checkedListBox1.Items.Count; j++)
checkedListBox1.SetItemChecked(j, false);
}
}

5.
得到全部選中的值 ,並將選中的項的文字組合成為一個字串。
string
strCollected = string.Empty;
for (int i = 0; i < checkedListBox1.Items.Count; i++)
{
if (checkedListBox1.GetItemChecked(i))
{
if (strCollected == string.Empty)
{
strCollected = checkedListBox1.GetItemText(
checkedListBox1.Items[i]);
}
else
{
strCollected = strCollected + "/" + checkedListBox1.
GetItemText(checkedListBox1.Items[i]);
}
}
}


6
.
設定CheckedListBox中第i項的Checked狀態
checkedListBox1.SetItemCheckState(i, CheckState.Checked);


7.
private void checkBoxAll_CheckedChanged(object sender, EventArgs e)
{
if (checkBoxAll.Checked)