[英]C#: How to add details to a DataTable and display it on a DataGridView without storing in the database
I want to store details to a DataTable when a button is pressed and display it on a DataGridView when the add button is pressed. 我想在按下按钮时将详细信息存储到DataTable,并在按下添加按钮时将其显示在DataGridView上。 How can I achieve this. 我该如何实现。 Please help me. 请帮我。 Thanks a lot. 非常感谢。
I tried this code. 我尝试了这段代码。 But I need a way to bind it with the datagrid. 但是我需要一种将其与数据网格绑定的方法。
DataRow dr;
DataTable dt=new DataTable();
dt.Columns.Add("LoginId", typeof(int));
dt.Columns.Add("UserFirstName", typeof(string));
dt.Columns.Add("LastName", typeof(string));
dt.Columns.Add("Password", typeof(string));
dt.Columns.Add("EmailId", typeof(string));
dt.Columns.Add("Role", typeof(string));
dt.Columns.Add("Description", typeof(string));
dr = dt.NewRow();
Here's the way to bind DataTable
on DataGridView
这是在DataGridView
上绑定DataTable
的方法
myDataGrid.DataSource = myDataTable;
myDataGrid.DataBind();
You can add columns to the datatable as you need, and then add rows, like this: 您可以根据需要向数据表中添加列,然后添加行,如下所示:
DataTable dt = new DataTable();
int value = 0;
private void Form1_Load(object sender, EventArgs e)
{
dataGridView1.AutoGenerateColumns = true;
dt.Columns.AddRange(new DataColumn[]
{
new DataColumn("column1", typeof(string)),
new DataColumn("column2", typeof(int)),
});
}
private void button1_Click(object sender, EventArgs e)
{
dt.Rows.Add("str value", value++);
dataGridView1.DataSource = dt;
}
In your given code you are not adding newly created row in data table, you can add row in data table like this 在给定的代码中,您不会在数据表中添加新创建的行,您可以像这样在数据表中添加行
dr = dt.NewRow();
dt.Rows.Add(dr);
GridView1.DataSource = dt;
GridView1.DataBind();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.