如何在组合框的DrawItem事件中获取DisplayMember值?C# 请考虑以下事项:
我使用以下方法填充组合框:如何在组合框的DrawItem事件中获取DisplayMember值?C# 请考虑以下事项:,c#,winforms,C#,Winforms,我使用以下方法填充组合框: void populateComboBox() { comboBox1.DataSource = GetDataTableSource(); // some data table used as source comboBox1.DisplayMember = "name"; // string comboBox1.ValueMember = "id"; // id is an int
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
事件中,我想获取组合框的DisplayMember
(名称)的值,并将其分配给某个变量。
到目前为止,我得到了这个代码,但它似乎不起作用。。。请把它改正一下。提前谢谢
void comboBox1_DrawItem(object sender, DrawItemEventArgs e)
{
string name = ((System.Data.DataRowView)(comboBox1.SelectedValue = e.Index))["name"].ToString();
// do something
//
}
仅使用组合框项目如何,它是选中的显示值:
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传递给泛型函数,则不希望将其传递给泛型函数 所以 背景 我在一个名为CalculateAndNetwidth的通用函数中使用了它。该函数循环遍历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);
}好的,我自己也遇到了这个问题,这里有一个更好的答案:
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属性
string displayValue = this.GetItemText(this.Items[e.Index]);
g.DrawString(displayValue, e.Font, br, e.Bounds.Left, y + 1);