Community discussion forum

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

  • 1 month 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

  • Advertisement

    Simply the fastest line-level profiler for .NET ever

    “The low overhead means it has minimal impact on the execution of my program”
    Mark Everest, Development Team Leader, Renault F1 Team Ltd.

    Try out the new ANTS Profiler 4 for yourself. Download your 14-day trial now

  • 1 month 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

  • 1 month 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];

  • 1 month 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).