Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add data to DataGridView

I'm having a Structure like

 X={ID="1", Name="XX",
    ID="2", Name="YY" };

How to dump this data to a DataGridView of two columns

The gridView is like

ID | Name

Can we use LINQ to do this. I'm new to DataGridView Pleaese help me to do this..

Thanks in advance

like image 592
Thorin Oakenshield Avatar asked Oct 13 '10 11:10

Thorin Oakenshield


2 Answers

first you need to add 2 columns to datagrid. you may do it at design time. see Columns property. then add rows as much as you need.

this.dataGridView1.Rows.Add("1", "XX");
like image 122
Arseny Avatar answered Oct 08 '22 05:10

Arseny


Let's assume you have a class like this:

public class Staff
{
    public int ID { get; set; }
    public string Name { get; set; }
}

And assume you have dragged and dropped a DataGridView to your form, and name it dataGridView1.

You need a BindingSource to hold your data to bind your DataGridView. This is how you can do it:

private void frmDGV_Load(object sender, EventArgs e)
{
    //dummy data
    List<Staff> lstStaff = new List<Staff>();
    lstStaff.Add(new Staff()
    {
        ID = 1,
        Name = "XX"
    });
    lstStaff.Add(new Staff()
    {
        ID = 2,
        Name = "YY"
    });

    //use binding source to hold dummy data
    BindingSource binding = new BindingSource();
    binding.DataSource = lstStaff;

    //bind datagridview to binding source
    dataGridView1.DataSource = binding;
}
like image 26
bla Avatar answered Oct 08 '22 04:10

bla