Can I programmatically add a row to a WPF datagrid?
I just want to add a new row, I have my datasource in objects in which I need to do some processing. i need something like below for wpf datagrid...
DataRow row = dataTable.N开发者_JAVA百科ewRow();
foreach (NavItem item in record.Items)
{
row[item.FieldNo.ToString()] = item.RecordValue;
}
dataTable.Rows.Add(row);
You should be using an ObservableCollection<NavItem>
as the datagrid source. Then simply adding a new element to your collection will add it to the datagrid.
See this MSDN article.
I do not know if it is the right solution, but I came up to something like this, in desperation:
foreach (NavField field in this.Fields)
{
DataGridTextColumn column = new DataGridTextColumn();
column.Header = field.FieldNo.ToString();
//Some other logic
// Hide non active and hidden fields
if (!field.Active || !field.Show)
column.Visibility = System.Windows.Visibility.Collapsed;
grid.Columns.Add(column);
}
Then I add the datatable as itemssource:
this.dataGridLines.ItemsSource = dataTable.DefaultView;
If I set the datatable directly, it does not care about the columns from the datatable and autogenerate its own columns, don't know why..
精彩评论