المساعد الشخصي الرقمي

مشاهدة النسخة كاملة : Populate Listview using LINQ



C# Programming
06-25-2011, 10:11 AM
Hi,

I'm trying to populate a listview control and my query is LINQ. I used one of the table (Production.Product) of AdventureWorks database.

At first i have problem populating the header, but i figured it out after an hour. The code below is the code on how to populate column in listview using LINQ.

Code:

//Sample result when you query using SQL Server.----------------------------------------------------------------------------------------------ProductID Name ProductNumber MakeFlag FinishedGoodsFlag Color----------------------------------------------------------------------------------------------317 LL Crankarm CA-5965 0 1 Black318 ML Crankarm CA-5938 0 1 Black319 HL Crankarm CA-5990 0 1 Black320 Chainring CA-5932 0 1 Black---------------------------------------------------------------------------------------------
//lvw = ListView control DataClasses1DataContext db = new DataClasses1DataContext(); DataTable dt = new DataTable();DataColumn dc = new DataColumn();DataRow dr; var products = from p in db.Products where p.Color != null select p; #region getHeadervar headers = products.First();foreach (var columnHeader in headers.GetType().GetProperties()){ lvw.Columns.Add(columnHeader.Name);}#endregion

Now, my problem is how do i populate the result of my query and add it to listview. Actually, i can populate it like this,

ListViewItem lstItem = null; foreach (var itms in products){ lstItem = new ListViewItem(itms.ProductID.ToString()); lstItem.SubItems.Add(itms.Name); lstItem.SubItems.Add(itms.ProductNumber); ..... and so on}
The problem on the above code is that, what if i have a 25 columns in my query result? I have to type in my code 25x the lstItem.SubItems.Add(value) which kinda hassle for me. I want my function in populating the listview to be dynamic. http://www.barakasoft.com/script/Forums/Images/smiley_smile.gif


Anyone out there can help me to solve my "simple (i think)" problem.


Thanks and regards
Jessie
if(you type your code here) {
Messagebox.Show("You help me a lot!");
}
else {
You help me = null;
}