Reputation: 1
I do not understand how to write content from a database to a DataGrid. Here is the code Code DataGrid
<DataGrid AutoGenerateColumns="False" x:Name="ColorsTable" HorizontalGridLinesBrush="DarkGray"
RowBackground="LightGray" AlternatingRowBackground="White" Grid.ColumnSpan="2" Margin="0,0,624.2,0">
<DataGrid.Columns>
<DataGridTextColumn Header="ID" Binding="{Binding Path = Id}" Width="100" />
<DataGridTextColumn Header="Name" Binding="{Binding Path = Name}" Width="100" />
<DataGridTextColumn Header="Specification" Binding="{Binding Path = Specification}" Width="100" />
</DataGrid.Columns>
</DataGrid>
Code add
ObservableCollection<SomeAbstact> temp = new ObservableCollection<SomeAbstact>();
sqlCommand = new SqlCommand("SELECT * FROM [Colors]", SqlConnection);
reader = await sqlCommand.ExecuteReaderAsync();
while (await reader.ReadAsync())
{
temp.Add(new Colors()
{
Id = Convert.ToInt32(reader["Id"]),
Name = reader["Name"].ToString(),
Specification = reader["Description"].ToString()
});
}
ColorsTable.ItemsSource = temp;
temp.Clear();
reader.Close();
Entity add
public class Colors: SomeAbstact
{
public int Id { get; set; }
public string Name { get; set; }
public string Specification { get; set; }
}
Upvotes: 0
Views: 77
Reputation: 43
You can bind the DataGrid
to the ObservableCollection
like this:
<DataGrid ItemsSource="{Binding temp}">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding Id}"/>
<DataGridTextColumn Binding="{Binding Name}"/>
<DataGridTextColumn Binding="{Binding Specification}"/>
</DataGrid.Columns>
</DataGrid>
This will only work if the DataContext
is set properly.
Also you should check out how to implement INotifyPropertyChanged
if you want to use bindings in WPF.
Upvotes: 1