日期:2014-05-18 浏览次数:21192 次
private void button2_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("性别");
dt.Columns.Add("1/0");
DataRow dr = dt.NewRow();
dr["性别"] = "男";
dr["1/0"] = "1";
dt.Rows.Add(dr);
comboBox1.DataSource = dt;
comboBox1.DisplayMember="性别";
comboBox1.ValueMember= "1/0";
comboBox1.SelectedIndexChanged += new EventHandler(comboBox1_SelectedIndexChanged);
}
void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
//throw new Exception("The method or operation is not implemented.");
MessageBox.Show(this.comboBox1.SelectedValue.ToString());
}
------解决方案--------------------
尽管 ComboBox 通常用于显示文本项,您仍可向 ComboBox 添加任何对象。
using System;
using System.Windows.Forms;
class Form1 : Form
{
Form1()
{
ComboBox combobox1 = new ComboBox();
combobox1.Parent = this;
combobox1.Items.Add(new Sex(1)); // 值为1,显示为 "男"
combobox1.Items.Add(new Sex(0)); // 值为0,显示为 "女"
}
static void Main()
{
Application.Run(new Form1());
}
}
struct Sex
{
public int sex;
public Sex(int sex)
{
this.sex = sex;
}
public override string ToString()
{
return sex == 0 ? "女" : "男";
}
}
------解决方案--------------------
1、定义一个类
Public Class cboTextValueItem
Private _text As String
Private _value As Integer
Public Sub New(ByVal text As String, ByVal value As Integer)
_text = text
_value = value
End Sub
Public Property Text() As String
Get
Return _text
End Get
Set(ByVal value As String)
_text = value
End Set
End Property
Public Property Value() As Integer
Get
Return _value
End Get
Set(ByVal value As Integer)
_value = value
End Set
End Property
[color=#FF0000]
'重要
Public Overrides Function ToString() As String
Return _text
End Function[/color]
End Class
------解决方案--------------------
comboBox1.Items.Insert(0, new ComboBoxItem("0","请选择"));
comboBox1.Items.Insert(1, new ComboBoxItem("1","根目录"));
internal class ComboBoxItem:Object
{
private string value;
private string text;
public ComboBoxItem(string _value, string _text)
{
value = _value;
text = _text;
}
public string Text
{
get { return text; }
}
public string Value
{
get { return value; }
}
public override string ToString()
{
return text;
}
}
------解决方案--------------------
using System;
using System.Windows.Forms;
class Form1 : Form
{
Form1()
{
ComboBox combobox1 = new ComboBox();
combobox1.Parent = this;
combobox1.Items.Add(new Sex(1)); // 值为1,显示为 "男"
combobox1.Items.Add(new Sex