Click here to Skip to main content
15,749,184 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am trying to show the contents of list in datagrid when an event is raised. See the code below

List<string> mlw = new System.Collections.Generic.List<int>();<br />
mlw.Add("qwe1");<br />
mlw.Add("qwe2");<br />
mlw.Add("qwe3");<br />
mlw.Add("qwe4");<br />
mlw.Add("qwe5");<br />
dataGrid1.ItemsSource = mlw;</int></string>

What I see the result I can see the space for 5 rows with "4" written in each of it

1 solution

The way WPF binding works, it tries to bind to a property of the object in the list. If one is not specified, then it will use the first property it finds (for strings this is the Length property). To get around this, I use LinQ and an anonymous type, something like this

List<string> mlw = new List<string>(){"qwe1","qwe2","qwe3","qwe4","qwe5"};
           var values = from str in mlw select new { value = str };
           dataGrid1.DataContext = values.ToList();

and this will show the actual string value

This is the xaml declaration

<DataGrid Name="dataGrid1" Grid.Row="4" ItemsSource="{Binding}" AutoGenerateColumns="True"/>

Hope this helps
Share this answer
Wayne Gaylard 4-Jul-11 6:09am    
Hi, the code I posted is already in c#. Here is the link for MSDN WPF binding page. Good Luck!.
Muhammad Waqas Iqbal 4-Jul-11 6:20am    
thanks for ur solution,
what to do if I want to bind to datagrid to sqldatareader? Do I need to extract all the sql data and put it in some var like in the above example?
Wayne Gaylard 4-Jul-11 6:31am    
In the case of data readers, I would suggest that you create a collection first, fill the collection from the data reader, close the data reader, then bind to the collection. Hope that helps
Muhammad Waqas Iqbal 4-Jul-11 6:51am    
Thanks again,
Hope I am not bothering you. Can you name any collection to store 15 column result from sqldatareader? If possible, send me the written code as you did in the above case. Also can dataset be used in such a case?
Wayne Gaylard 4-Jul-11 7:02am    
You need to create a Class that has properties that correspond to your database fields. Then you can use a datareader to convert the db fields to your class type, adding each one to a collection as you go. I am afraid I am too busy to write the code. I am sure you are up to it. Good Luck!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900