[英]How i can add new row into datagrid in wpf?
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 我试图为按钮的每次单击插入DataGrid的所有Rows值,所以如果用户在datagrid上插入了三次显示三行,则我有一个类有代码
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;
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 . 这段代码可以正常工作,但是有一个问题,当添加数据应该显示在一行中,但是一次单击却出现在3行中时,我想用不同的数据在每次单击中显示一行。 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. 首先这不是做WPF的方法。 Use proper bindings to achieve you want. 使用适当的绑定来实现您想要的。
Steps to do in WPF way: 以WPF方式执行的步骤:
ObservableCollection<MyGrid>
and bind ItemsSource with that collection. 创建ObservableCollection<MyGrid>
并将ItemsSource与该集合绑定。 INotifyCollectionChanged
. 自ObservableCollection实现INotifyCollectionChanged
以来,DataGrid将自动刷新。 Now, for your code there are couple of issues. 现在,对于您的代码,有几个问题。
Remove the for loop
. Remove the for loop
。 initialize list only once from class constructor
. 而是将列表保留为实例字段,并initialize list only once from class constructor
。 No need to set ItemsSource again
with every button click. No need to set ItemsSource again
每次单击按钮都No need to set ItemsSource again
。 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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.