How To Use C# To Connect Dictionary Elements To A DataGridView In Windows Application Forms

Learn how to bind the dictonary items in a datagrid in this article.

var dictionary = new Dictionary<string, object>();
for (int k = 0; k < dt.Rows.Count - 1; k++)
{
dictionary.Add(dt.Rows[k][ColumnName].ToString(),dt.Rows[k][ColumnName]);
}
var bindingSource1 = new BindingSource();
bindingSource1.DataSource = dictionary.ToList();

dataGridView1.DataSource = bindingSource1.DataSource;
dataGridView1.AllowUserToAddRows = false;

for (int i = 0; i < dataGridView1.RowCount - 1; i++)
{
dataGridView1.Rows[i].Cells[0].Value = dictionary.Select(r => r.Key).ToList()[i];
dataGridView1.Rows[i].Cells[1].Value = dictionary.Select(k => k.Value).ToList()[i];
}

 

 

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories