asdasdad
asdasdad

Reputation: 862

How to show only a substring of an item in a ComboBox in C#

I have some Company names as Items in a ComboBox like this:

123 SomeCompany

Always a number between 100 and 999 plus the company name.

Now if the user selects an Item I want the TextBox to only show the number, not the company name. he company name should only be visible when he drops down the ComboBox...

I tried to set ComboBox1.Text = ComboBox.Text.Substring(0, 3) in the SelectedIndexChanged-Event and the TextChanged-Event, but it didn't do anything, there was always everything in the ComboBox...

AutocompleteMode is set to none.

What did I do wrong?

Upvotes: 1

Views: 3222

Answers (3)

stay_hungry
stay_hungry

Reputation: 1448

Try something like this:

private void combox1_ SelectedIndexChanged(object sender,EventArgs e)
{
      string value = (combox1.selectedItem != null) ? 
          combox1.selectedItem.ToString().Substring(0, 3) : string.Empty;
}

Upvotes: 0

Talha
Talha

Reputation: 19242

Try this

textbox1.Text = ComboBox1.SelectedItem.ToString().SubString(0, 3);

Upvotes: 0

Me.Name
Me.Name

Reputation: 12534

To always format the value, you could use the Format event (with FormattingEnabled = true)

    private void comboBox1_Format(object sender, ListControlConvertEventArgs e)
    {   
          e.Value = e.Value.ToString().Substring(0, 3);
    }

But if you want the full value to be displayed when the dropdown is shown, you can temporarily disable the formatting:

    private void comboBox1_DropDown(object sender, EventArgs e)
    {
        comboBox1.FormattingEnabled = false;
    }

    private void comboBox1_DropDownClosed(object sender, EventArgs e)
    {
        comboBox1.FormattingEnabled = true;
    }

Upvotes: 4

Related Questions