ComboBox的扩展,添加了只读Value属性,和SelectedByValue及SelectedByText两个方法
| 方法或属性 |
介绍 |
| Text |
原控件属性 |
| Value |
等价于ComboBox绑定状态的SelectedValue,或非绑定状态的:Text |
| SelectedByValue(object obj) |
绑定状态时根据ValueMember选择,非绑定状态时根据SelectedItem选择。精确查找 |
| SelectedByText(object obj) |
绑定状态时根据DisplayMember选择,非绑定状态时根据SelectedItem选择。精确查找 |
使用示例:
comboBoxEx1.Text
comboBoxEx1.Value
comboBoxEx1.SelectedByValue("2");
comboBoxEx1.SelectedByText("Name3");
控件主要代码:
using System;
using System.Windows.Forms;
//web:http://www.yongfa365.com/
namespace YongFa365.Controls.ComboBoxEx
{
public partial class ComboBoxEx : ComboBox
{
public ComboBoxEx()
{
this.DropDownStyle = ComboBoxStyle.DropDownList;
}
public void SelectedByValue(object obj)
{
if (this.DataSource == null)
{
//非绑定时
this.SelectedItem = obj;
}
else
{
object preValue = this.SelectedValue;
//绑定时直接查找
this.SelectedValue = obj;
if (this.SelectedValue == null)
{
//查不到保持原控件值不变
this.SelectedValue = preValue;
}
}
}
public void SelectedByText(object obj)
{
if (this.DataSource == null)
{
//非绑定时
this.SelectedItem = obj;
}
else
{
//绑定时
this.Text = obj.ToString();
}
}
public string Value
{
get
{
if (this.DataSource == null)
{
//非绑定时返回Text
return this.Text;
}
else
{
//绑定时返回SelectedValue
return this.SelectedValue.ToString();
}
}
}
}
}
下载地址:ComboBoxEx.rar
引用本页地址:
http://www.yongfa365.com/item/ComboBoxEx.html