我如何在WPF中将新行添加到DataGrid中? [英] How i can add new row into datagrid in wpf?

查看:41
本文介绍了我如何在WPF中将新行添加到DataGrid中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图为按钮的每次单击插入DataGrid的所有Rows值,因此,如果用户在datagrid的三行显示中插入了三遍,我就有一个类,有代码

I'm trying to Insert all Rows values of DataGrid for Once every Click of a button , so if user inserted three times display on datagrid three rows,I have a class there is code

    public string Name { get; set; }
    public string Job { get; set; }
    public string Phone { get; set; }

    public MyGrid(string Vendors,string Jobs,string Tel)
    {
        Name = Vendors;
        Job = Jobs;
        Phone = Tel;
    }

我在这里打电话给按钮点击事件

and i called into button click event here

       static List<MyGrid> gride;
        gride = new List<MyGrid>();
        for (int i = 0; i < 3; i++)
        {
            var myg1 = new MyGrid(textBox10.Text, textBox11.Text, textBox12.Text);
            gride.Add(myg1);

        }

        dataGridView1.ItemsSource = gride; 

此代码可以正常工作,但是有一个问题,当添加数据应该显示在一行中,但是在一键中出现在3行中时,我想在每次点击中显示不同数据的一行.我如何在wpf中单击按钮添加新行

this code it's working but there is the one problem,When add data is supposed to appear in a one row, but appears within 3 rows in the one click , I want to show one row in per click with different data . How i can add new row per click on the button in wpf

推荐答案

首先,这不是WPF方法.使用适当的绑定来实现您想要的.

First of all this is not a way to do WPF way. Use proper bindings to achieve you want.

以WPF方式执行的步骤:

Steps to do in WPF way:

  1. 创建 ObservableCollection< MyGrid> 并将ItemsSource与该集合绑定.
  2. 代替再次设置ItemsSource,只需在该集合中添加对象.自ObservableCollection实现 INotifyCollectionChanged 以来,DataGrid将自动刷新.


现在,对于您的代码,有几个问题.


Now, for your code there are couple of issues.

  1. 如果要一次添加项目,为什么要运行循环并添加对象三次. 删除for循环 .
  2. 单击每个按钮,即可重新初始化列表.而是将列表保留为实例字段,并仅通过类构造函数 初始化列表一次.
  3. 无需再次设置ItemsSource .


public class CodeBehindClass
{
   private ObservableCollection<MyGrid> gride;
   public CodeBehindClass()
   {
      gride = new ObservableCollection<MyGrid>();
      dataGridView1.ItemsSource = gride;
   }

   private void ButtonHandler(object sender, RoutedEventArgs e)
   {
      var myg1 = new MyGrid(textBox10.Text, textBox11.Text, textBox12.Text);
      gride.Add(myg1);
   }
}

这篇关于我如何在WPF中将新行添加到DataGrid中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆