Reputation: 59
In my code I have 2 listboxes and 1 datagridview.I want to get listbox1 data to datagridview1 column0 and listbox2 data to datagridview column1?
foreach (var item in listBox1.Items)
{
dataGridView1.Rows.Add();
dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells[0].Value = item;
dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells[1].Value = listBox2.Items;
}
Upvotes: 0
Views: 5732
Reputation: 142
Create a datattable with the required columns and bind it to gridview.
DataTable dt = new DataTable();
dt.Columns.Add("Column1",typeof(datatype));//column 0
dt.Columns.Add("Column2",typeof(datattype));//column 1
if(ListBox1.Items.Count == ListBox2.Items.Count)
{
for (int i = 0; i < ListBox1.Items.Count; i++)
{
dt.Rows.Add(ListBox1.Items[i].Text, ListBox2.Items[i].Text);
}
dataGridView1.DataSource = dt;
dataGridView1.DataBind();
}
Upvotes: 0
Reputation: 7067
item
represents an item stored in the ListBox. So if you'd like to grab the value of the selected one and show it in the datagrid then:
dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells[0].Value = listBox1.SelectedItems[0].ToString();
it takes the first selected item's value into grid.
Upvotes: 2
Reputation: 22841
Try this out:
dataGridView1.AutoGenerateColumns = false;
dataGridView1.Rows.Clear();
listBox1.Items.Add("1");
listBox1.Items.Add("2");
listBox1.Items.Add("3");
dataGridView1.Columns.Add("First","First");
foreach (var item in listBox1.Items)
{
int idx = dataGridView1.Rows.Add();
dataGridView1.Rows[idx].Cells["First"].Value = item;
}
Sample output:
Upvotes: 3