Need to populate a Datagrid in UWP with a Datatable. I could display the contents by following: https://stackoverflow.com/a/53767049/12053338
However, I am unable to edit the datagrid.
How do I make the Datagrid editable? (tired setting IsReadOnly to false).
Thanks
XAML
<controls:DataGrid
x:Name="grid"
IsReadOnly="False"
VerticalAlignment="Stretch"
HorizontalAlignment="Stretch"
GridLinesVisibility="All">
</controls:DataGrid>
C#
//Datatable
var table = new DataTable("Students");
table.Columns.Add(new DataColumn() { ColumnName = "Name", DataType = typeof(string)});
table.Columns.Add(new DataColumn() { ColumnName = "Id", DataType = typeof(string)});
//Add a row
table.Rows.Add("Akinator","1");
//Conversion of datatable to datagrid itemsource
for (int i = 0; i < table.Columns.Count; i )
{
grid.Columns.Add(new DataGridTextColumn()
{
Header = table.Columns[i].ColumnName,
Binding = new Binding { Path = new PropertyPath("[" i.ToString() "]"), Mode = BindingMode.TwoWay, UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged }
});
}
var collection = new ObservableCollection<object>();
foreach (DataRow row in table.Rows)
{
if (row.ItemArray.Length > 0)
collection.Add(row.ItemArray);
}
grid.ItemsSource = collection;
*Usage of data table cannot be substituted in this particular case.
CodePudding user response:
I have figured out the solution to this, Set IsReadonly to false while creating the columns
//Conversion of datatable to datagrid itemsource
for (int i = 0; i < table.Columns.Count; i )
{
grid.Columns.Add(new DataGridTextColumn()
{
Header = table.Columns[i].ColumnName,
Binding = new Binding { Path = new PropertyPath("[" i.ToString() "]"), Mode = BindingMode.TwoWay, UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged },
IsReadOnly = false //ADD THIS TO MAKE THE DATAGRID EDITABLE
});
}
var collection = new ObservableCollection<object>();
foreach (DataRow row in table.Rows)
{
if (row.ItemArray.Length > 0)
collection.Add(row.ItemArray);
}
grid.ItemsSource = collection;