1:winForm ComboBox 控件默认值绑定及只可选择不可输入设定处理
最经需要开发一个winForm应用程序,里面用到了ComboBox 空间,首先遇到的问题是不知道如何绑定Text和Value到ComboBox 控件;其次是绑定到ComboBox控件上的内容居然可以修改,让人茫然;最后就是ComboBox选择的值不能够在代码中取得,郁闷啊。经过在网上资料的收集整理先将问题整理如下:
1、ComboBox中同时绑定Text和Value
首先要定义一个简单数据存放的类,定义如下:
- public class MyItem
- {
- public MyItem(string Text, string Value)
- {
- this.Text = Text;
- this.Value = Value;
- }
- public MyItem() {
- this.Text = "http://www.my400800.cn";
- this.Value = "http://blog.my400800.cn";
- }
- private string _Text;
- public string Text
- {
- get { return _Text; }
- set { _Text = value; }
- }
- private string _Value;
- public string Value
- {
- get { return _Value; }
- set { _Value = value; }
- }
- public override bool Equals(System.Object obj)
- {
- if (this.GetType().Equals(obj.GetType()))
- {
- MyItem that = (MyItem)obj;
- return (this.Text.Equals(that.Value));
- }
- return false;
- }
- public override int GetHashCode()
- {
- return this.Value.GetHashCode(); ;
- }
- }
ComboBox控件数据添加代码如下:
其中 cbl是ComboBox控件的一个实例:
- cbl.Items.Clear();
- cbl.DisplayMember = "Text";
- cbl.ValueMember = "Value";
- cbl.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
- List<MyItem> items = new List<MyItem>();
- MyItem item = new MyItem();
- item.Text = "男";
- item.Value = "1";
- items.Add(item);
- item = new MyItem();
- item.Text = "女";
- item.Value = "2";
- items.Add(item);
- item = new MyItem();
- item.Text = "未知";
- item.Value = "3";
- items.Add(item);
- //将数据源的属性与ComboBox的属性对应
- cbl.DisplayMember = "Text"; //显示
- cbl.ValueMember = "Value"; //值
- cbl.DataSource = items;
- cbl.SelectedValue = "3";
2、ComboBox控件上的内容不可修改设定方法
- cbl.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
3、ComboBox选择取得
- combox_Department.SelectedValue
在上面的数据绑定大ComboBox是不要用下面的方式,不然的话用cbl.SelectedValue取不到值。
MyItem item = new MyItem();
item.Text = "男";
item.Value = "1";
items.Add(item);
item = new MyItem();
cbl.Items.Add(items);
转载:http://blog.csdn.net/ljl_xyf/article/details/4551687
public class TestInfo
{
string _strName;
object _objValue;
public string GetName
{
get { return _strName; }
set { this._strName = value; }
}
问题:
http://topic.csdn.net/u/20100709/09/6576e409-3402-4a58-ab08-ea96a8c4ef9b.html
先定义这个类
然后
Dictionary<string,string> d = new Dictionary<string,string>();
d.add("HHAA000000AAAC00","人事課");//后面一样的加
List<TestInfo> t = new List<TestInfo>();
最后
Foreach(KeyValuePare<string,string> s in d)
{
TestInfo ti = new TestInfo();//就是上面的那个类
ti.GetName = s.Value;
ti.GetValue = s.Key;
t.add(ti);
}
this.comboBox1.DataSource = t;
this.comboBox1.ValueMember = "GetValue";
this.comboBox1.DisplayMember = "GetName";
最后 ,如果你要得到对应的编码的话
this.ComboBox1.SelectedValue就能得到了
List<KeyValuePair<object, string>> dit = new List<KeyValuePair<object, string>>();
dit.Add(new KeyValuePair<object, string>(1, "厦门"));
dit.Add(new KeyValuePair<object, string>(2, "上海"));
this.comboBox1.DataSource = dit;
this.comboBox1.DisplayMember = "Value";
this.comboBox1.ValueMember = "Key";