需求:向ListBox“listBox1”中动态添加和删除项,每项包含一个显示Text和一个实际值Value

注意问题:ListBox和ComboBox在显示任意类型(object)的item时调用的是item类的ToString()方法,如果这个item类没有重载ToString(),那么显示的结果就是命名空间   +   类名。

(1)首先定义一个类Item_valuetext,这是向listBox1中添加的Item的类型。

public class Item_valuetext

{

        private string display;

        private string truevalue;

 

        public Item_valuetext(string name, string text)

        {

            this.display = text;

            this.truevalue = name;

        }

        public override string ToString()     //重载ToString()方法

        {

            return this.display;

        }

 

        public string Display

        {

            get

            {

                return this.display;

            }

            set

            {

                this.display = value;

            }

        }

 

        public string Value

        {

            get

            {

                return this.truevalue;

            }

            set

            {

                this.truevalue=value;

            }

        }

}

(2)向listBox1中动态添加Item_valuetext类型的item

public void ListItemAdd(string ItemValue,string ItemText)

{

        Item_valuetext ItemAdded = new Item_valuetext(ItemValue, ItemText);

        this.listBox1.Items.Add(ItemAdded);

        this.listBox1.DisplayMember = "Display";

        this.listBox1.ValueMember = "Value";

} 

(3)删除listBox1中选择的一项或多项(listBox允许多选的前提条件:this.listBox1.SelectionMode = System.Windows.Forms.SelectionMode.MultiSimple;)

public void ListItemDelete()

{

        if (this.listBox1.SelectedItems.Count == 0)

            MessageBox.Show("Please select at least one item");

        else

        {

            while (this.listBox1.SelectedItems.Count > 0)

                 this.listBox1.Items.Remove(this.listBox1.SelectedItems[0]);

        }

}

(4)在richTextBox1中显示listBox1每项的Value

private void ShowItemValue()

{

        foreach (object t in this.listBox1.Items)

        {

                Item_valuetext item = (Item_valuetext)(t);

                this.richTextBox1.Text += item.Value+"\n";

        }

}

(5)将listBox1中的每一项添加到comboBox1中

private void AddtoCombo()

{

        foreach (object t in this.listBox1.Items)

        {

                this.comboBox1.Items.Add(t);

        }

}

posted on 2008-12-01 18:13  Jessica Lu  阅读(1006)  评论(2)    收藏  举报