简体   繁体   中英

Fill DataGridView from checkedListBox

I have a checkedListBox1 and i want to convert all it's items to a DataGridView i have the following code

 string[] ar = new string[60];
        for (int j = 0; j < checkedListBox1.Items.Count; j++)
        {
            ar[j] = checkedListBox1.Items[j].ToString();
        }
        dataGridView2.DataSource = ar;

but the dataGridView2 is filled with the length of the item instead of the item itself, can any one help?

These code blocks may give an idea (all is worked for me). CheckedListBox items returns a collection. It is coming from IList interface so if we use a List item as datasource for datagridview solves the problem. I used generic List as an additional class of Sample . When we use string array datagridview shows each items length. In here overried ToString returns original value.

class Sample
{
   public string Value { get; set; }

   public override string ToString()
   {
       return Value;
   }
}

In form class:

private void button1_Click(object sender, EventArgs e)
{
  CheckedListBox.ObjectCollection col = chk.Items;
  List<Sample> list = new List<Sample>();
  foreach (var item in col)
  {
      list.Add(new Sample { Value = item.ToString() });
  }

  dgw.DataSource = list;

 }

This simple DataTable code appears to work...

DataTable dt = new DataTable();
dt.Columns.Add("Name", typeof(string));
for (int j = 0; j < checkedListBox1.Items.Count; j++) {
  dt.Rows.Add(checkedListBox1.Items[j].ToString());
}
dataGridView1.DataSource = dt;

Because DataGridView looks for properties of containing objects. For string there is just one property - length. So, you need a wrapper for a string like this.

string[] ar = new string[60];
for (int j = 0; j < checkedListBox1.Items.Count; j++)
{
    ar[j] = checkedListBox1.Items[j].ToString();
}
dataGridView1.DataSource = ar.Select(x => new { Value = x }).ToList();

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