简体   繁体   English

如何在C#中使用子字符串从组合框获取值

[英]How to get value from combobox using substring in C#

I have a combo box which have item strings like: 我有一个组合框,其项目字符串如下:

1 .  Apple
2 .  Banana
3 .  Mango 

1,2,3 are category id & Apple, Banana, Mango is Category Name. 1,2,3是类别ID和Apple,香蕉,芒果是类别名称。

I want to know Category Id From comboBox using Category name which is sub-string of ComboBox item. 我想知道类别ID来自comboBox使用类别名称,它是ComboBox项目的子字符串。

example: 例:

I want to know the Category Id of Banana. 我想知道香蕉的类别ID。 which is 2. 这是2。

Any help ? 有帮助吗?

Use this code to an event that should be after you selected the item in comboBox : 将此代码用于在comboBox中选择项目后应该发生的事件:

        string []str;
        str = comboBox1.Text.Split(' ');
        string categoryId = str[0];

Try the following code. 请尝试以下代码。 It will give the CategotyId of the selected Category. 它将给出所选类别的CategotyId

private void ComboBox1_SelectedIndexChanged(object sender, System.EventArgs e) {
    string selectedText = comboBox1.SelectedText;
    string categoryId  = selectedText.Substring(0, selectedText.IndexOf(" "));

    MesasgeBox.Show(categoryId);
}
    foreach (object item in cmb.Items)
    {
      string[] str = item.ToString().split(new char[] {' '}
, StringSplitOptions.RemoveEmptyEntries);
      if(str[1] == "Banana")
      {
           Console.Write(str[0]);
      }
    }

@Pranay Rana Your Answer Helped me: I wrote my method like that @Pranay Rana你的答案帮助我:我这样写了我的方法

private string get_Godown_id(string godown_name)
    {
        foreach (object item in cb_send_to.Items)
        {
            if (item.ToString().Split('.')[1].Trim() == godown_name)
            {
                return (item.ToString().Split('.')[0]);
            }
        }
        return "";
    }
foreach (object item in cb_send_to.Items)
    {
        if (item.ToString().Split('.')[1].Trim() == godown_name)
        {
            return (item.ToString().Split('.')[0]);
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM