请考虑以下事项:
我使用以下方法填充我的comboBox:
void populateComboBox()
{
comboBox1.DataSource = GetDataTableSource(); // some data table used as source
comboBox1.DisplayMember = "name"; // string
comboBox1.ValueMember = "id"; // id is an int
// Suppose I have this data in my comboBox after populating it
//
//
// id (ValueMember) | name (DisplayMember)
// -----------------------------------------
// 1 | name1
// 2 | name2
// 3 | name3
}
在DrawItem
事件中,我想获得comboBox的DisplayMember
(名称)的值并将其分配给某个变量。到目前为止,我得到了这个代码,它似乎不工作…请把它改过来。提前感谢....
void comboBox1_DrawItem(object sender, DrawItemEventArgs e)
{
string name = ((System.Data.DataRowView)(comboBox1.SelectedValue = e.Index))["name"].ToString();
// do something
//
}
好吧,我自己也遇到过这个问题,这里有一个更好的答案:
string displayValue = this.GetItemText(this.Items[e.Index]);
g.DrawString(displayValue, e.Font, br, e.Bounds.Left, y + 1);
每MSDN: 如果未指定DisplayMember属性,则返回的值为GetItemText是该项的ToString方法的值。否则,方法中指定的成员的字符串值在item参数
中指定的对象的DisplayMember属性。
http://msdn.microsoft.com/en-us/library/system.windows.forms.listcontrol.getitemtext (v = vs.80) . aspx
如何使用组合框项,它被选中显示值:
string name = (string)comboBox1.Items[e.Index];
如果你得到e.Index = -1
,改变DrawMode = OwnerDrawVariable
和DropDownStyle = DropDown
好吧,我知道怎么了。我测试了字符串作为数据源,所以在你的代码应该这样工作:
string name = ((DataRowView)comboBox1.Items[e.Index])["name"];
如果你想创建一个真正通用的函数,你可以详细说明一下:
假设你有两个组合框,一个包含基于带有DisplayMember AA的自定义集合A的项目,另一个包含基于带有DisplayMember BB的自定义集合B的项目:
泛型函数如何知道返回哪个值?当然是基于DisplayMember的,但是如果你想让它泛型,你就不想把AA/BB传递给泛型函数。
[anItemTheCombobox.GetType().GetProperty(theCombobox.DisplayMember).GetValue(theCombobox, null)];
的背景我在一个叫做calculateAndSetWidth的泛型函数中使用了它。该函数循环遍历listbox中的所有项,以确定maxWidth:
public void calculateAndSetWidth(ListBox listbox, int minWidth = 0) {
Graphics graphics = this.CreateGraphics();
int maxWidth = 0;
SizeF mySize = null;
foreach (object item in listbox.Items) {
mySize = graphics.MeasureString(item.GetType().GetProperty(listbox.DisplayMember).GetValue(item, null), listbox.Font);
if (mySize.Width > maxWidth) {
maxWidth = mySize.Width;
}
}
listbox.Width = Math.Max(maxWidth, minWidth);
}