从C#中的组合框项设置typeof值

时间:2016-09-01 16:02:17

标签: c# combobox

我是C#的新手,我通过编码而不是连接到外部数据库来创建一个简单的表。我有一个Combobox(下拉列表),以便用户可以从下拉列表项中选择列的数据类型,然后将所选项设置为列的数据类型。我需要这一行中的所选项目:

            customer.Columns.Add(cn , typeof(long));

这是我的全班:

 namespace HomeWork1
 {
 public partial class Form1 : Form
 {
    public String tn;
    public String cn;
    DataTable customer;
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        comboBox1.Items.Add("Boolean");
        comboBox1.Items.Add("Byte");
        comboBox1.Items.Add("Char");
        comboBox1.Items.Add("DateTime");
        comboBox1.Items.Add("Decimal");
        comboBox1.Items.Add("Double");
        comboBox1.Items.Add("Int16");
        comboBox1.Items.Add("Int32");
        comboBox1.Items.Add("Int64");
        comboBox1.Items.Add("String");
    }

    private void button1_Click(object sender, EventArgs e)
    {
        tn = txtTableName.Text;

        customer = new DataTable(tn);
    }

    private void button2_Click(object sender, EventArgs e)
    {
        cn = txtColumnName.Text;
        customer.Columns.Add(cn , typeof(long));
        dataGridView1.DataSource = customer;
    }
 }
 }

1 个答案:

答案 0 :(得分:1)

C#区分大小写。 combobox1comboBox1不一样。由于您的组合框名为comboBox1,大写字母为“B”,因此请将其写为:

customer.Columns.Add(cn ,
    Type.GetType("System." + (string)comboBox1.SelectedItem));
'                                         ^ upper case "B"

您可以拥有两个仅在大写/小写不同的变量:

int x = 1;
int X = 100;

这些实际上是两个不同的变量!

注意:获取Type对象有不同的方式:

  1. 从类型

    Type t = typeof(int); // typeof(int) is known at compile time.
    
  2. 来自对象

    Type t = someObject.GetType(); // Known only at runtime.
    
  3. 从作为字符串

    给出的类型名称
    string s = "System.Int32";
    Type t = Type.GetType(s);
    
  4. 注意:GetType()是一种所有类型都从System.Object继承的方法。

    由于组合框中有类型名称字符串,请使用第三个版本。

    Type t = Type.GetType("System." + (string)comboBox1.SelectedItem);
    customer.Columns.Add(cn , t);
    

    或直接将Type个对象添加到组合框而不是字符串:

    comboBox1.Items.Add(typeof(bool));
    comboBox1.Items.Add(typeof(byte));
    

    然后只需使用

    获取类型
    Type t = (Type)comboBox1.SelectedItem;
    customer.Columns.Add(cn , t);