How to get the DisplayMember value in the DrawItem event of a comboBox? C#

Viewed 16236

Please consider the following:

I populate my comboBox using the following method:

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
}

In DrawItem event, I want to get the value of the DisplayMember (name) of the comboBox and assign it to some variable. So far, I got this code and it seems not to work... Please have it corrected. Thanks in advance....

void comboBox1_DrawItem(object sender, DrawItemEventArgs e)
{
    string name = ((System.Data.DataRowView)(comboBox1.SelectedValue = e.Index))["name"].ToString();

    // do something
    //  
}
3 Answers

Ok, i just came across this problem myself and here is an even better answer:

string displayValue = this.GetItemText(this.Items[e.Index]);             
g.DrawString(displayValue, e.Font, br, e.Bounds.Left, y + 1);

Per 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

Related