在取得combBox項目的值时遇到一些问题,现在将问题解决方法发布如下:
测试代码:
1.测试用类,主要用来想combBox中添加数据项
InBlock.gif public class Vendor
InBlock.gif        {
InBlock.gif                
InBlock.gif                 private int old;
InBlock.gif                 private string name;
InBlock.gif                 public string Name
InBlock.gif                {
InBlock.gif                        get
InBlock.gif                        {
InBlock.gif                                 return name;
InBlock.gif                        }
InBlock.gif                        set    
InBlock.gif                        {
InBlock.gif                                 this.name = value;
InBlock.gif                        }
InBlock.gif                }
InBlock.gif                 public int Old
InBlock.gif                {
InBlock.gif                        get { return old; }
InBlock.gif                        set { old = value; }
InBlock.gif                }
InBlock.gif                 public Vendor( string na, int ol)
InBlock.gif                {
InBlock.gif                        name = na;
InBlock.gif                        old = ol;
InBlock.gif                }
InBlock.gif                 public Vendor()
InBlock.gif                {}
InBlock.gif        }
添加数据的代码:(初始化时....)
            comboBox1.Items.Add(new Vendor("aaa",5));
            comboBox1.Items.Add(new Vendor("dddd", 66));
            comboBox1.DisplayMember = "Old";
            comboBox1.ValueMember = "Name";
其中DisplayMember设置显示的数据,下面那个是对应的值,也就是待会要取出来的值.
以下是显示的代码(将值显示出来)
InBlock.gif                        var k = ((Vendor)comboBox1.SelectedItem).Name;
InBlock.gif                        MessageBox.Show(k.ToString());
直接selecteditem是一个object的对象,所以需要将它转化成Vendor然后才能取到name值,代码测试通过。。。有兴趣的试试!
2.模拟绑定数据库的
InBlock.gif                        comboBox1.DataSource = null;
InBlock.gif                        ArrayList lst = new ArrayList();
InBlock.gif                        lst.Add( new Vendor( "aaaaaa", 1111111));
InBlock.gif                        lst.Add( new Vendor( "aa", 11));
InBlock.gif                        lst.Add( new Vendor( "aaaa", 11111));
InBlock.gif                        lst.Add( new Vendor( "aaaaa", 11111));
InBlock.gif                        comboBox1.Items.Clear();
InBlock.gif                        comboBox1.DataSource = lst;
InBlock.gif                        comboBox1.DisplayMember = "Name";
InBlock.gif                        comboBox1.ValueMember = "Old";
以下是显示的代码:
InBlock.gif                                var k = ( int)comboBox1.SelectedValue;    
InBlock.gif                                MessageBox.Show(k.ToString());
就这么多,网上好多问答的很模糊有不懂的再留言!