Naqib Shayea Naqib Shayea - 1 year ago 151
C# Question

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()

private void Form1_Load(object sender, EventArgs e)

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;

Answer Source

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

    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:


Then simply get the type with

Type t = (Type)comboBox1.SelectedItem;
customer.Columns.Add(cn , t);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download