如何在 C# WPF 中向数据网格添加行

本文关键字:数据 数据网 网格 添加行 WPF | 更新日期: 2023-09-27 18:19:22

我在 C# WPF 中向数据网格添加行时遇到问题。

我为数据做了一个结构:

public struct MyData
{
    public int id { set; get; }
    public string title { set; get; }
    public int jobint { set; get; }
    public DateTime lastrun { set; get; }
    public DateTime nextrun { set; get; }
}

以及添加数据的方法:

  private void Add_Data_Grid_Row(object sender, RoutedEventArgs e)
        {
            Button button = sender as Button;
            DockPanel panel = button.Parent as DockPanel;
            DataGrid usedDataGrid = panel.Children.OfType<DataGrid>().FirstOrDefault();
            usedDataGrid.Items.Add(new MyData { id = 11123, title = "King", jobint = 1993123, lastrun = DateTime.Today, nextrun = DateTime.Today  });
        }

你能以某种方式帮助我吗?

如何在 C# WPF 中向数据网格添加行

        DataTable dt = new DataTable();
        DataColumn column;
        DataRow row;
        DataView view;
        row = new DataRow();
        dt.Rows.Add(row);
        column = new DataColumn();
        column.DataType = System.Type.GetType("System.Int32");
        column.ColumnName = "id";
        dt.Columns.Add(column);
        column = new DataColumn();
        column.DataType = Type.GetType("System.String");
        column.ColumnName = "item";
        dt.Columns.Add(column);
        for (int i = 0; i < 10; i++)
        {
            row = dt.NewRow();
            row["id"] = i;
            row["item"] = "item " + i.ToString();
            dt.Rows.Add(row);
        }
        view = new DataView(dt);
        dataView1.ItemsSource = view;

其中 dataView1 = 数据网格的名称。

 //Use ObservableCollection
 public ObservableCollection<MyData> MySource {get;set;}
 //initialize once, eg. ctor
 this.MySource = new ObservableCollection<MyData>();
 //add items
 this.MySource.Add(new MyData { id = 11123, title = "King", jobint = 1993123, lastrun = DateTime.Today, nextrun = DateTime.Today});
 //set the itemssource
 usedDataGrid.ItemsSource = this.MySource;

或者采用 MVVM 方式并使用绑定而不是代码隐藏并设置 itemssource如果未将自动生成列设置为 true,则必须使用绑定定义列

 <DataGrid ItemsSource="{Binding MySource}" AutogenerateColumns="true"/>

如果DataGrid绑定到数据源,则在控件中添加/操作行的常用方法不是作用于控件本身(仅显示绑定数据源的内容(,而是尝试简单地添加/操作数据源本身的内容,例如,向结构集合添加新的结构条目,DataGrid将立即反映此类新条目。

您必须将 DataGrid 绑定到 ObservableCollection。现在,每当向 ObservableCollection 添加新项时,DataGrid 都会使用最新更改进行刷新。

请看这个例子:http://www.codeproject.com/Articles/42536/List-vs-ObservableCollection-vs-INotifyPropertyCha

数据结构必须实现枚举接口。对于此功能,您可以将其添加到 ObservableCollection 或任何实现 IEnumerable 的类中(如列表,但这不提供可观察性,但将数据添加到列表中(,因此这为您提供了基本的 WPF 元素实现此外,您还必须实现 INotifyPropertyChange 接口,用于有关模型绑定事件操作(如果这是您的必需品(。