DataGrid with empty DataTable allowing user input C # WPF
I have an application with multiple tabs, each containing a Datagrid that contains data from my database. I have a save button that writes all datagrids to a .csv file. I want to create an additional tab containing an empty datagrid so that the user can enter information so that it can output the same way.
Is there a way to bind the datagrid to an empty data table? Or is there a better solution that will allow the user to dynamically enter variable amounts of information (sometimes one line, 10 times)
FROM#
DataTable dt_Call_Drivers = new DataTable();
Call_Drivers_DataGrid.ItemsSource = dt_Call_Drivers.DefaultView;
XAML
<DataGrid x:Name="Call_Drivers_DataGrid" ItemsSource="{Binding}" GridLinesVisibility="Horizontal" CanUserAddRows="true" AutoGenerateColumns="False" Margin="0,0,0,0">
<DataGrid.ColumnHeaderStyle>
<Style TargetType="{x:Type DataGridColumnHeader}" BasedOn="{StaticResource MetroDataGridColumnHeader}">
<Setter Property="HorizontalContentAlignment" Value="Center" />
</Style>
</DataGrid.ColumnHeaderStyle>
<DataGrid.Columns>
<DataGridTextColumn Header="Case" Width ="90" Binding="{Binding Case}">
<DataGridTextColumn.ElementStyle>
<Style>
<Setter Property="TextBlock.TextAlignment" Value="Center" />
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
</DataGrid.Columns>
</DataGrid>
+3
source to share
1 answer
Just bind datagrid to ObservableCollection, define your type. And set CanUserAddRows = true. It's all.
<DataGrid CanUserAddRows="True" AutoGenerateColumns="False" ItemsSource="{Binding SimpleCollection}">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding A}"></DataGridTextColumn>
<DataGridTextColumn Binding="{Binding B}"></DataGridTextColumn>
<DataGridTextColumn Binding="{Binding C}"></DataGridTextColumn>
</DataGrid.Columns>
</DataGrid>
public class SimpleClass
{
public string A { get; set; }
public string B { get; set; }
public string C { get; set; }
}
private ObservableCollection<SimpleClass> _simpleCollection;
public ObservableCollection<SimpleClass> SimpleCollection
{
get { return _simpleCollection ?? (_simpleCollection = new ObservableCollection<SimpleClass>()); }
set { _simpleCollection = value; }
}
+2
source to share