How to assign the ItemsSource of a DataGrid with code behind?

981 Views Asked by At

I have a DataGrid in my XAML:

<DataGrid x:Name="dataGridBasket" Width="270" AutoGenerateColumns="True" 
ItemsSource="{Binding Path=LoadDataBindingBasket}" HorizontalAlignment="Left" Margin="10,5,0,10" />

I have some code to run a SQL query and assign the results to the grid:

DataSet dataSetBespokeBasket = new DataSet();
MySqlDataAdapter adp = new MySqlDataAdapter(mySqlCommand);
adp.Fill(dataSetBespokeBasket, "LoadDataBindingBasket");
dataGridBasket.DataContext = dataSetBespokeBasket; 

Question: Is there a way to leave out the ItemsSource="{Binding Path=LoadDataBindingBasket}" and just assign that in the C# code? It is a little clumsy to have to be bound to that name I assigned in the XAML, I'd like to be able to modify it at runtime for various use cases.

1

There are 1 best solutions below

0
BionicCode On BEST ANSWER

You must select the appropriate DataTable from DataSet.Table and assign it to DataGrid.ItemsSource:

var dataSet = new DataSet();
...

this.dataGridBasket.ItemsSource = dataset.Tables["MyDtabaseTablename"].DefaultView;