Home > Enterprise >  Windows Forms Combo Box Text doesn't update when I manually change the text in the SelectedValu
Windows Forms Combo Box Text doesn't update when I manually change the text in the SelectedValu

Time:12-01

I have the following code

private void cbAddTicketItem_SelectedValueChanged(object sender, EventArgs e)
{
     string[] arr = cbAddTicketItem.Text.Split(' ');
     cbAddTicketItem.Text = arr[0];
}

cbAddTicketItem is the combo box where the user is selecting from a list of items. The text of each item includes a description. I want to get rid of the description and just keep the value. Debugging shows that cbAddTicketItem.Text has the correct value but the text doesn't change on the form.

I think the issue is that either winforms is not firing the textChanged event, or it is overwriting it after my coded event runs.

CodePudding user response:

You're making life rather hard work. It's easier if you do something like this:

var dt - new DataTable();
dt.Columns.Add("Disp");
dt.Columns.Add("Val");
dt.Rows.Add("Mark","1");
dt.Rows.Add("Luke","2");
dt.Rows.Add("John","3");

someCombo.DisplayMember = "Disp";
someCombo.ValueMember = "Val";
someCombo.DataSource = dt;

And then in some button click, let's say:

MessageBox.Show((string)someCombo.SelectedValue); //shows 2 if Luke is selected, etc
  • Related