Reputation: 597
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. 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();
Upvotes: 0
Views: 1081
Reputation: 2363
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();
Upvotes: 1
Reputation: 2392
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;
}
Upvotes: 1
Reputation: 263813
Here's the way to bind DataTable
on DataGridView
myDataGrid.DataSource = myDataTable;
myDataGrid.DataBind();
Upvotes: 2