如何在C#WPF中向Datagrid添加行

时间:2014-08-26 08:26:28

标签: c# wpf datagrid

我在C#WPF中向Datagrid添加行时遇到问题。

我为数据做了一个Struct:

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  });

        }

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

5 个答案:

答案 0 :(得分:1)

 //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的方式使用Binding而不是代码隐藏并设置itemssource 如果你没有将AutogenerateColumns设置为true,则必须使用绑定

来定义列
 <DataGrid ItemsSource="{Binding MySource}" AutogenerateColumns="true"/>

答案 1 :(得分:1)

        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 = Datagrid的名称。

答案 2 :(得分:0)

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

答案 3 :(得分:0)

您必须将DataGrid绑定到ObservableCollection。现在每当你向ObservableCollection添加一个新项时,DataGrid都会刷新最新的更新。

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

答案 4 :(得分:0)

您的数据结构必须实现一个枚举接口。对于这个feture,您可以将它添加到ObservableCollection或任何实现IEnumerable的类(如列表,但这不提供observablity但将数据添加到列表),这样就可以为您提供基本的WPF元素实现 此外,如果有必要,您必须实现INotifyPropertyChange接口以关注模型绑定事件操作。

相关问题