有没有办法将组合框中的选定项目转换为代码?

时间:2019-12-13 02:42:11

标签: c#

我想将用户在组合框中选择的项目转换为可执行程序集,因此我可以直接从类中输出,而无需编写单独的if语句。我确实对此进行了搜索,但找不到适合我的答案。我为lblOne.Text = cboComboBox.SelectedItem.aString遇到的错误消息是:'object'不包含'aString'的定义,并且找不到可访问的扩展方法'aString'接受类型为'object'的第一个参数(您是否缺少using指令或程序集引用?)。抱歉,如果我发布了太多代码,这是我第二次在这里发布。这是我尝试编写的代码:

// in public partial class Form1: Form    : A one = new A("One", "Cool");

public class A
    {

        // Instance Variables 
        string Name;
        string Info;

        // Constructor Declaration of Class 
        public A(string Name, string Info)
        {
            this.Name = Name;
            this.Info = Info;
        }

        // method 1 
        public string getName()
        {
            return Name;
        }

        // method 2 
        public string getInfo()
        {
            return Info;
        }

       //output to label

        public string aString()
        {
            return ("Name: " + this.getName() + "\n" +
                    "Info: " + this.getInfo() + "\n");
        }

    private void btnStats_Click(object sender, EventArgs e)
    {
        lblOne.Text = cboComboBox.SelectedItem.aString();
        //doesn't actually work
        //what I want it to be in code: lblOne.Text = one.aString();
    }

1 个答案:

答案 0 :(得分:0)

组合框/列表框等​​的

SelectedItem属性将所选项目作为对象返回。
使用该属性之前,需要将其强制转换为类类型

((YourClassName)comboBox.SelectedItem).YourProperty

(comboBox.SelectedItem as YourClassName).YourProperty