When we bind a list with a control like datagridview, comboBox or listbox, then it will bind all the fields related to list. I have created a list of student with multiple fields i.e. Name, age, city and DOB. Now in this article I will bind only name and age of this list to a Datagridview.
To get selected fields, syntax of LINQ query will be:
Now in our case of Student class the records should be selected through the following C# line of code:
In the last line of code, it will bind the list to gridview and show only name and age of the students like in following image:
If all the LINQ methods are not showing in your program then sure about the namespace in your code file i.e. System. Linq;
See Also: How to Bind DataGridView with DataSet
To get selected fields, syntax of LINQ query will be:
var variable = from tempVar in list
select new
{
tempVar.Field1,
tempVar.Field2
};
select new
{
tempVar.Field1,
tempVar.Field2
};
Now in our case of Student class the records should be selected through the following C# line of code:
var selectedFields = from s in stuList
select new
{
s.Name,
s.Age
};
dataGridView1.DataSource = selectedFields.ToList();
select new
{
s.Name,
s.Age
};
dataGridView1.DataSource = selectedFields.ToList();
In the last line of code, it will bind the list to gridview and show only name and age of the students like in following image:
If all the LINQ methods are not showing in your program then sure about the namespace in your code file i.e. System. Linq;
See Also: How to Bind DataGridView with DataSet