您的位置:首页 > 产品设计 > UI/UE

Winform开发之ComboBox和ComboBoxEdit控件绑定key/value数据

2017-07-04 01:30 417 查看
使用 ComboBox 控件绑定key/value值:

因为 ComboBox 是有 DataSource 属性的,所以它可以直接绑定数据源,如 DataTable、ListItem 等。

使用 DataTable 直接绑定:

     public void BindSource()
{
DataTable dt = new DataTable();
dt.Columns.Add("Text", Type.GetType("System.String"));
dt.Columns.Add("Value", Type.GetType("System.String"));

dt.Rows.Add("请选择", "0");
dt.Rows.Add("选项一", "1");
dt.Rows.Add("选项二", "2");
dt.Rows.Add("选项三", "3");

comboBox1.DataSource = dt;
comboBox1.DisplayMember = "Text";   // Text,即显式的文本
comboBox1.ValueMember = "Value";    // Value,即实际的值
comboBox1.SelectedIndex = 0;        //  设置为默认选中第一个
}


string text = this.comboBox1.Text;      //获取选中项文本
string value = this.comboBox1.SelectedValue.ToString();     //获取选中项的值


使用 ListItem 实现 key/value:

public class ListItem : Object
{
public string Text { get; set; }

public string Value { get; set; }

public ListItem(string text,string value)
{
this.Text = text;
this.Value = value;
}

public override string ToString()
{
return this.Text;
}
}


public void BindSource()
{
List<ListItem> list = new List<ListItem>();

list.Add(new ListItem("请选择", "0"));
list.Add(new ListItem("选项一", "1"));
list.Add(new ListItem("选项二", "2"));
list.Add(new ListItem("选项三", "3"));

comboBox1.DisplayMember = "Text";   // Text,即显式的文本
comboBox1.ValueMember = "Value";    // Value,即实际的值
comboBox1.DataSource = list;
comboBox1.SelectedValue = "0";        //  设置选择值为 0 的项
}


string text = (this.comboBox1.SelectedItem as ListItem).Text;      //获取选中项文本
string value = (this.comboBox1.SelectedItem as ListItem).Value;     //获取选中项的值


使用 ComboBoxEdit 控件绑定key/value值:

因为 ComboBoxEdit 没有 DataSource 属性,所以不能直接绑定数据源,只能一项一项的添加。

public class ListItem : Object
{
public string Text { get; set; }

public string Value { get; set; }

public ListItem(string text,string value)
{
this.Text = text;
this.Value = value;
}

public override string ToString()
{
return this.Text;
}
}


public void BindSource()
{
string text = string.Empty;
string value = string.Empty;

ListItem item = null;

for (int i = 0; i < 4; i++)
{
if (i==0)
{
text = "请选择";
}
else
{
text = "选项" + i.ToString();
}
value = i.ToString();

item = new ListItem(text, value);
this.comboBoxEdit1.Properties.Items.Add(item);
}
}


获取选中项的值时,注意判断是否选择。

string text = string.Empty;
string value = string.Empty;

if (comboBoxEdit1.SelectedIndex < 0)    //小于0,表示未选择,如果是输入的也小于0
{
text = comboBoxEdit1.Text.Trim();     //只能获取输入的文本
}
else
{
text= (comboBoxEdit1.SelectedItem as ListItem).Text;        //获取选中项文本
value = (comboBoxEdit1.SelectedItem as ListItem).Value;        //获取选中项的值
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: