code to get the first character of the words in Combo box in C#

  • 11 years ago

     

    Hello Gurus,

    Can any body help me with the C# code to get the first character of the words for selected element from drop down Combo box.

     

    Thanks,

    RN

  • 11 years ago

    Given a comboBox and a textBox, this might help you:

    private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)

    {

      String selectedItem = comboBox1.SelectedItem.ToString();

      textBox1.Text = selectedItem.Substring(0, selectedItem.IndexOf(" "));

    }

    HTH

  • 11 years ago

    Just one issue, when you have less than two words : an exception, because 'IndexOf()' returns '-1'. You can use 'Split()' to do it properly :

    textBox1.Text = selectedItem.Split(' ')[0];

  • 11 years ago

    We are both wrong!   I misread the original question :-)

    The code should be:

    String selectedItem = comboBox1.SelectedItem.ToString();

    string[] a = selectedItem.Split(' ');

    textBox2.Text = "";

    foreach (string s in a)

    {

      textBox2.Text = textBox2.Text + s.Substring(0, 1);

    }

    HTH

Post a reply

Enter your message below

Sign in or Join us (it's free).

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.” - Brian Kernighan