在CheckedListBox中,怎样判新添加的项不能与CheckedListBox中已有项相同?另外,还有一问题?
怎么把CheckedListBox中选中的项删除,我写了如下代码,还是不得行.运行执行没有反应.
for (int i = 0; i < CheckedListBox1.Items.Count; i++)
{
  if (CheckedListBox1.GetItemChecked(i))
  {
    CheckedListBox1.Items.Remove(i);
    CheckedListBox1.Refresh();
  }
}麻烦大家指导一下这两个问题?
非常感谢!

解决方案 »

  1.   

    添加:
            string additem = "aa";//要添加的项
            int flag = 0;
            for (int i = 0; i < CheckBoxList1.Items.Count; i++)
            {
                if (CheckBoxList1.Items[i].Text == additem)
                {
                    flag = 1;
                    break;
                }
            }
            if (flag == 1)
                Response.Write("不能添加!!");
            else
            {
                CheckBoxList1.Items.Add(additem);
            }删除:
            int index = 1;//要删除项的索引号
            CheckBoxList1.Items.Remove(CheckBoxList1.Items[index]);
      

  2.   

    你可以给CheckBox中每个记录设置哈希键值对,然后判断。。
      

  3.   


                if (checkedListBox1.Items.IndexOf("123") < 0)//如果没有123
                    checkedListBox1.Items.Add("123");//那就插入123
    Remove后面跟的是项的引用,要根据索引来删除,应该用RemoveAt方法
      

  4.   

    public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }        private void Form1_Load(object sender, EventArgs e)
            {
                this.checkedListBox1.Items.Add("飞飞");
                this.checkedListBox1.Items.Add("丽丽");
            }        private void button1_Click(object sender, EventArgs e)
            {
                if (this.textBox1.Text.Trim().Equals(""))
                {
                    MessageBox.Show("请输入名字");
                    return;
                }
                else
                { 
                    for(int i = 0;i < this.checkedListBox1.Items.Count;i++)
                    {
                        if (this.textBox1.Text.Equals(this.checkedListBox1.Items[i]))
                        {
                            MessageBox.Show("已有相同名称存在,请重新输入");
                            this.textBox1.Text = "";
                            return;
                        }
                            
                    }
                    this.checkedListBox1.Items.Add(this.textBox1.Text);
                    
                }
            }        private void checkedListBox1_SelectedIndexChanged(object sender, EventArgs e)
            {
                
            }        private void button2_Click(object sender, EventArgs e)
            {
                for (int i = 0; i < this.checkedListBox1.Items.Count; i++)
                {
                    if (this.checkedListBox1.GetItemChecked(i))
                    {
                        this.checkedListBox1.Items.RemoveAt(i);
                    }
                }
            }
        }