如何在类构造函数的c#中的datagrid中添加一行 [英] how to add one row in datagrid in c# on class constructor
本文介绍了如何在类构造函数的c#中的datagrid中添加一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
晚上好!在 C#WPF 中创建的项目中,我使用datagrid为用户提供一个用户必须填写的空表,但我无法向我的数据网格添加行。我还想让他有机会通过点击按钮或完成一行来添加空行。提前谢谢你。
Good evening! in a project created in C# WPF , I am using datagrid to give the user an empty table that the user has to fill in but I could not add a Rows to my datagrid. I would also like to give him the opportunity to add a blank line either by clicking on a button or completing a line. Thank you in advance.
推荐答案
It is not so difficult you have to create a list or observeable collection and then have to bind it with your datagrid.Then when you wanna add new row just add item in your list.
As shown bellow
In XAMP:
<window x:class="WpfApplication2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<grid>
<datagrid autogeneratecolumns="True" height="233" horizontalalignment="Left" margin="66,21,0,0" name="dataGrid1" verticalalignment="Top" width="354"></datagrid>
<button content="Add Row" height="27" horizontalalignment="Left" margin="66,260,0,0" name="button1" verticalalignment="Top" width="72" click="button1_Click" />
</grid>
</window>
In code behind(C#)
public partial class MainWindow : Window
{
List<employee> lstEmployee = new List<employee>();
public MainWindow()
{
InitializeComponent();
dataGrid1.CanUserAddRows=true;
}
void AddItemAndBind(int id)
{
Employee emp = new Employee();
emp.ID = id;
lstEmployee.Add(emp);
dataGrid1.ItemsSource = lstEmployee;
}
public class Employee
{
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
public string City { get; set; }
public string Phone { get; set; }
}
private void button1_Click(object sender, RoutedEventArgs e)
{
AddItemAndBind(lstEmployee.Count+1);
}
}
这篇关于如何在类构造函数的c#中的datagrid中添加一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文