views:

68

answers:

5

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

A: 

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");
Arseny
I've added two columns at the design time. now i need to display the data in that `grid view`
Pramodh
Thank you ... I need to iterate through the structure. So i've to use `for` or `foreach` loop. can we use `LAMBDA` expression for this?
Pramodh
yes. there are many options. I guess you may use databinding as the best one
Arseny
A: 

LINQ is a "query" language (thats the Q), so modifying data is outside its scope.

That said, your DataGridView is presumably bound to an ItemsSource, perhaps of type ObservableCollection<T> or similar. In that case, just do something like X.ToList().ForEach(yourGridSource.Add) (this might have to be adapted based on the type of source in your grid).

danijels
A: 

you shoud do like this form your code

DataGridView.DataSource = yourlist;

DataGridView.DataBind();

Profeten
A: 

My favorite way to do this is with an extension function called 'Map':

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

Then you can add all the rows like so:

X.Map(item => this.dataGridView1.Rows.Add(item.ID, item.Name));
diceguyd30
A: 

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;
}
Lee Sy En
You don't need a binding source. You can assign the list directly to the grids DataSource.
Mystere Man
Yes we don't need a binding source, we can bind the list to grid's Datasource directly. The advantage of using bindingsource is that we can refresh binding source later if the list has changed/updated. The grid will get the refresh as well.
Lee Sy En