HDuck
HDuck

Reputation: 395

C# How to append a character to a listbox DisplayMember?

I have a listbox with a datatable bound to it. The datatable has two columns, "CMM" and "Location". "CMM" is a one/two digit integer which is used as the DisplayMember for the listbox, and "Location" is a one digit integer, equal to 1 or 2. If the Location column is equal to 2 I would like to add an asterisk to what is displayed in the listbox. I am trying to avoid using drawitem for the listbox.

Upvotes: 3

Views: 262

Answers (1)

mnieto
mnieto

Reputation: 3874

You can use the ListBox.Format event to conditionally change the shown value

EDIT: Added an example:

At design time, You'll need to create a ListBox control and assign the DisplayMember property to CMM

private void Form1_Load(object sender, EventArgs e) {
    DataTable dt = InitData();
    listBox1.DataSource = dt;
}

private static DataTable InitData() {
    DataTable dt = new DataTable();
    dt.Columns.Add("CMM", typeof(int));
    dt.Columns.Add("Location", typeof(int));
    DataRow row = dt.NewRow();
    row["CMM"] = 25;
    row["Location"] = 1;
    dt.Rows.Add(row);
    row = dt.NewRow();
    row["CMM"] = 26;
    row["Location"] = 2;
    dt.Rows.Add(row);
    row = dt.NewRow();
    row["CMM"] = 27;
    row["Location"] = 21;
    dt.Rows.Add(row);
    return dt;
}

private void listBox1_Format(object sender, ListControlConvertEventArgs e) {
    //We assigned dataTable with DataRows, but e.ListItem is DataRowView ¿?
    DataRowView rowView = e.ListItem as DataRowView;
    if (rowView != null) {
        e.Value = ((int)rowView.Row["Location"] == 2) ? "*" + rowView.Row["CMM"].ToString() : rowView.Row["CMM"];
    }
}

Upvotes: 3

Related Questions