How to query a DataSet and set the result as a DataSource for some control? (C# winforms)
I'm digging in in my Microsoft Visual Studio Documentation and I found this article under C# Reference (ms-help://MS.VSCC.v90/MS.MSDNQTR.v90.en/dv_csref/html/df01e266-5781-4aaa-80c4-67cf28ea093f.htm), It's about Interface Interface
. Here's the example code:
class SelectSample1
{
static void Main()
{
//Create the data source
List<int> Scores = new List<int>() { 97, 92, 81, 60 };
开发者_如何学Python // Create the query.
IEnumerable<int> queryHighScores =
from score in Scores
where score > 80
select score;
// Execute the query.
foreach (int i in queryHighScores)
{
Console.Write(i + " ");
}
}
}
//Output: 97 92 81
Instead of a List
, is it also possible to query a DataTable
and set the result of the query as the DataSource of a DataGridView
?
If yes, suppose I have this structure:
Fruit | CategoryID
---------------------------------------
Lemon | 1
Orange | 1
Apple | 2
Pear | 2
Can anyone please give me an example (if possible, for a beginner's approach.. :). What I want is to display the result in a DataGridView. Display all fruits where its CategoryID is equal to 1. Please help,
Thanks in advance guys.
You need to use AsEnumerable() extension of Databe to select the rows and bind to DataGridView like this:
DataTable table = new DataTable();
table.Columns.Add("Fruit");
table.Columns.Add("ID", typeof(int));
table.Rows.Add(new object[] { "Lemon", 1 });
table.Rows.Add(new object[] { "Orange", 1 });
table.Rows.Add(new object[] { "Apple", 2 });
table.Rows.Add(new object[] { "Pear", 2 });
BindingSource bs = new BindingSource();
bs.DataSource = from row in table.AsEnumerable()
where row.Field<int>("ID") == 1
select new {Fruit = row.Field<string>("Fruit"), ID = row.Field<int>("ID")};
dataGridView1.DataSource = bs;
Try this
var results = from row in dataTable.AsEnumerable()
where row.Field<int>("CategoryID") == 1
select row ;
and you can bind the result row easily to your control.
精彩评论