简体   繁体   中英

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.

try something like this

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM