How to add data to a DataGridView

I have a structure like

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

How to dump this data in DataGridViewfrom two columns

gridView is similar to

ID | Name

Is it possible to use LINQ for this. I'm new to DataGridView. Help me do this.

Thanks in advance

+3
source share
5 answers

first you need to add 2 columns to the datagrid. you can do this during development. see Columns Property. then add as many lines as you need.

this.dataGridView1.Rows.Add("1", "XX");
+15
source

Suppose you have a class like this:

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

And suppose you drag and drop DataGridViewinto your form and name it dataGridView1.

BindingSource, DataGridView. :

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;
}
+3

, "":

public static void Map<T>(this IEnumerable<T> source, Action<T> func)
{
    foreach (T i in source)
        func(i);
}

:

X.Map(item => this.dataGridView1.Rows.Add(item.ID, item.Name));
+2

LINQ - ( Q), .

, DataGridView ItemsSource, , ObservableCollection<T> . - X.ToList().ForEach(yourGridSource.Add) (, , ).

0

you shoud do like this code of your code

DataGridView.DataSource = your list;

DataGridView.DataBind ();

0
source

Source: https://habr.com/ru/post/1769324/


All Articles