首页 > 解决方案 > 有没有办法将组合框中的选定项目转换为代码?

问题描述

我想将用户在组合框中选择的项目转换为可执行程序集,这样我就可以直接从类中输出,而无需编写单独的 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();
    }

标签: c#

解决方案


组合框/列表框等​​的 SelectedItem 属性将所选项目作为Object返回。
在使用该属性之前,您需要将其转换为您的类类型

((YourClassName)comboBox.SelectedItem).YourProperty

或者

(comboBox.SelectedItem as YourClassName).YourProperty

推荐阅读