Wednesday, October 07, 2009

WPF ComboBox select item when using ItemsSource

I have a WPF ComboBox that is databound to a Linq query.

var mylinqdata = from d in DataTable0.AsEnumerable()


select new


{


Status = d.Field<string>(0).Trim(),


Progress = d.Field<string>(1).Trim()


};


 


dlg.cb_Status.ItemsSource = mylinqdata;




When data is bound to a WPF control using ItemsSource you must change the selected item using SelectedIndex. Here is the code I use.



dlg.cb_Status.SelectedIndex = mylinqdata.ToList().FindIndex(d => d.Status == loom.Status);


Here is the XAML of the ComboBox


<ComboBox Name="cb_Status">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path=Progress}"></TextBlock>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>

Friday, October 02, 2009

Linq group by multiple columns

Here is a bit of linq to group by multiple columns. It’s not very well documented so I’ve included a sample below.The trick is to use an anonymous type after the group by clause.

var data3 = from d in db.Assembly_V2s
group d by new { Column1 = d.AssemblyID / 100, Column2 = d.Description.Trim() } into g
orderby g.Key.Column1
select new { Column1 = g.Key.Column1, Column2 = g.Key.Column2 };