gpt4 book ai didi

c# - 如何在组合框的 DrawItem 事件中获取 DisplayMember 值? C#

转载 作者:太空狗 更新时间:2023-10-29 18:15:20 26 4
gpt4 key购买 nike

请考虑以下事项:

我使用以下方法填充我的组合框:

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 displayValue = this.GetItemText(this.Items[e.Index]);             
g.DrawString(displayValue, e.Font, br, e.Bounds.Left, y + 1);

根据 MSDN:

If the DisplayMember property is not specified, the value returned by GetItemText is the value of the item's ToString method. Otherwise, the method returns the string value of the member specified in the DisplayMember property for the object specified in the item parameter

http://msdn.microsoft.com/en-us/library/system.windows.forms.listcontrol.getitemtext(v=vs.80).aspx

关于c# - 如何在组合框的 DrawItem 事件中获取 DisplayMember 值? C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6954821/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com