修剪SelectedItem ComboBox

时间:2013-07-23 07:55:11

标签: c# winforms combobox trim

我有这个comboBox项目:

A6 - Tiger
A79 - Eagle
B6789- Elephant
B69679 - Monkey
C67 - Whale
D - Dragon

如何将selectedItem显示到textBox中只有字符串Tiger,Eagle Elephant ...没有A6,A79,B6789 ??

我在使用固定数量的char时使用了这个:

string temp = comboBox1.Text;
char[] array1 = temp.ToCharArray();
textBox1.Text = "" + array1[0] + array1[1];

4 个答案:

答案 0 :(得分:2)

假设你有SelectedItem

textBox1.Text = theSelectedItem.Split('-')[1].Trim()

答案 1 :(得分:1)

我假设“A6 - Tiger”是你文本的格式。
你可以试试这个:

            if (comboBox1.SelectedIndex > 0)
        {
            textBox1.Text = comboBox1.Text.Substring(comboBox1.Text.IndexOf('-') + 1).Trim();
        }

答案 2 :(得分:0)

您的代码在我看来就像您只想显示A6,A79,B6789,...... 所以我发布了两个解决方案

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{//Last
    string s = (string)listBox1.SelectedItem;

    string last = s.Substring(s.LastIndexOf(' ') + 1);

    textBox1.Text = last;

    listBox1_SelectedIndexChanged_first(sender, e);
}


private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{//First
    string s = (string)listBox1.SelectedItem;
    string first = s.Substring(0, s.IndexOf(' '));

    textBox1.Text = first;
}

答案 3 :(得分:0)

这应该有效

  string[] splittedValues =  comboBox1.Text.Trim().Split('-');
  if(splittedValues.Length==2)
      textBox1.Text = splittedValues[1].Trim();