mssaggoo.blogspot.in
mssaggoo.blogspot.in

Reputation: 121

How to Add Columns from DataTable to ComboBox in C#

I have a ComboBox and a DataSet. I want to add each DataColumn to ComboBox as ComboBox Item. I have tried this code:

DataColumn[] column_collection=new DataColumn[dataset.Tables[0].Columns.Count];
dataset.Tables[0].Columns.CopyTo(column_collection, 0);
combo_box.Items.AddRange(column_collection);

However, problem is that I just get a Empty List when I open ComboBox. That list has same number of items as there are columns, however there is no Value in it.

Upvotes: 1

Views: 2560

Answers (2)

mssaggoo.blogspot.in
mssaggoo.blogspot.in

Reputation: 121

Instead of:

combo_box.Items.AddRange(column_collection);

Write this:

    for (int i = 0; i < column_collection.Length;i++)
    {
        combo_box.Items.Add(column_collection.GetValue(i).ToString());
    }

Upvotes: 0

Selman Gen&#231;
Selman Gen&#231;

Reputation: 101701

try something like this

var columns = dataset.Tables[0].Columns
              .OfType<DataColumn>()
              .Select(c => c.ColumnName);

combo_box.Items.AddRange(columns.ToArray());

Upvotes: 2

Related Questions