Search code examples
c#combobox

Setting the typeof value from combobox Items in C#


I am new to C# and I am making a simple table by coding not connecting to an external database. I have a Combobox (Dropdown List) so that the user can select the data type of the Column from dropdown list items and then that selected Item is set as the data type of the Column. I need the selected item in this line :

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

and this is my whole class :

 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;
    }
 }
 }

Solution

  • C# is case sensitive. combobox1 and comboBox1 are not the same. Since your combo box is named comboBox1 with an upper case "B", write it like this:

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

    You can have two variables which differ only in upper / lower case:

    int x = 1;
    int X = 100;
    

    These are really two different variables!


    Note: there are different ways of getting a Type object:

    1. From a type name given as identifier

       Type t = typeof(int); // typeof(int) is known at compile time.
      
    2. From an object

       Type t = someObject.GetType(); // Known only at runtime.
      
    3. From a type name given as string

       string s = "System.Int32";
       Type t = Type.GetType(s);
      

    Note: GetType() is a method all types inherit from System.Object.


    Since you have type name strings in your combo box, use the third version.

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

    Or directly add Type objects to your combo box instead of strings:

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

    Then simply get the type with

    Type t = (Type)comboBox1.SelectedItem;
    customer.Columns.Add(cn , t);