Click here to Skip to main content
15,888,816 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi All,

I have one unbound datagridview with four columns.

I want to bind the list to first column/single column in the datagridview.

How can i make in windows C#??

Regards,
Mohana
Posted

1 solution

If your list contains values and not objects you could use this code:
C#
DataGridViewRow newRow;

foreach(var item in yourList)
{
   newRow = new DataGridViewRow(); 
   newRow.Cells[0].Value = item;
   yourDataGridView.Rows.Add(newRow);
}


On the other hand if your list contains (reference type) objects you'll have to change your column to DataGridViewComboBoxColumn, then bind values from your list to comboBox control used by DataGridViewComboBoxColumn and then use code from above.

This is general approach for binding values from list to comboBox:
C#
//binding list to DataGridViewComboBoxColumn
//you have to create List of KeyValuePair object in order to 
//properly bind values from original list to the comboBox
List<keyvaluepair><string,yourobjecttype>> listForBinding = new List<keyvaluepair><string,yourobjecttype>>();
foreach(var item in yourList)
{
   listForBinding.Add(new <string,yourobjecttype>(item.ToString(),item));
}

yourDataGridViewComboBoxColumn.DisplayMember = "Key";
yourDataGridViewComboBoxColumn.ValueMember = "Value";
yourDataGridViewComboBoxColumn.DataSource = listForBinding; 


//code from first block goes here
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900