从ComboBox获取文本 [英] get text from ComboBox

查看:161
本文介绍了从ComboBox获取文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

伙计们

我有一个包含项目的组合框.

条目条目将为1:Apple,2:Grape和181:Mango

我想做的就是将数字值放在:
前面
谁能帮忙

谢谢

Hi Guys

I have a ComboBox with items in.

The items entry will be 1:Apple, 2:Grape , up to 181:Mango

What i want to do is to get the number value in front of the :

Can anyone please help

Thanks

推荐答案

可以,但这是错误的方法.

正确的方法是:不要将字符串存储在ComboBox的列表中,存储某些类或结构的实例:

You can but this is wrong approach.

The right approach is: don''t store strings in the list of the ComboBox, store instances of some class or structure:

class ItemHelper {
    internal ItemHelper(string name, int id) {
        this.fName = name; this.fId = id;
    }
    public override void ToString() {
        return string.Format("{0}:{1}", this.fId, this.fName);
    }
    internal Name { get { return fName; } }
    internal Id { get { return fId; } }
    string fName;
    int fId;
}



为什么ToString被覆盖?定义项添加到列表(ComboBox或任何其他列表,还有TreeView)时如何以字符串形式显示.

这样,您可以以可靠的方式直接访问Id,而无需任何字符串技巧.好吧,您需要将所需的项目投射到ItemHelper.

—SA



Why ToString is overridden? To define how the item is presented in the string form when added to the list (of ComboBox or any other list, also a TreeView).

This way, you can access to the Id directly, without any string tricks, in a reliable way. Well, you will need to cast the item you need to ItemHelper.

—SA


使用hte字符串类的split方法在:上进行分割.然后使用int.TryParse解析数组中的第一个字符串.

字符串[] s = comboBox1.Text.Split(new char [] {'':''});
int n;

如果(int.TryParse(s [0],out n))
{
//成功.

}
USe the split method of hte string class to split on the :. Then use int.TryParse to parse the first string in the array.

string [] s = comboBox1.Text.Split( new char[] { '':'' } );
int n;

if (int.TryParse(s[0], out n))
{
// success.

}


如果选择了 1:Apple ,则需要1.正确吗?
尝试ComboBox1.SelectedText.Split(new char[]{'':''})[0]
If 1:Apple is selected, you want 1. Right?
Try ComboBox1.SelectedText.Split(new char[]{'':''})[0]


这篇关于从ComboBox获取文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆