Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataGridView: Add new row using an array or List<t>

I've two listbox-elements in my form. The items in listbox1 are representing the columns in my DataGridView, the items in my listbox2 are representing the rows in my DataGridView.

foreach (var el in listBox1Elements)
{
// code...
dataGridView1.Columns.Add(col);
}

Since items in listbox1 can be added or deleted I've a problem with my current solution.

dataGridView1.Rows.Add("test","some","data","even","more","data");

I wonder if there is a solution for using a List. Then my code could look something like this:

foreach (var el in listBox2Elements)
{
   myList.add("some text");
}
dataGridView1.Rows.Add(myList);
like image 223
Kesandal Avatar asked Feb 18 '23 21:02

Kesandal


2 Answers

Something like

        foreach (var el in listBox2Elements)
            myList.add("some text");

        foreach (var item in myList)
            dataGridView1.Rows.Add(item.., item.., item..);

or

dataGridView1.DataSource = myList.ToList()
like image 162
spajce Avatar answered Feb 20 '23 11:02

spajce


How about:

foreach (var el in listBox2Elements)
{
   myList.add("some text");
}
dataGridView1.Rows.Add(myList.ToArray());
like image 20
Michael Murphy Avatar answered Feb 20 '23 12:02

Michael Murphy