How to update DataGrid on click event?
I have the following code which updates the data base on a button click by calling a function additems.
static DataTable additems(string itema, string itemb, string itemc, string itemd)
开发者_C百科 {
DataTable listitems = new DataTable();
listitems.Columns.Add("itema");
listitems.Columns.Add("itemb");
listitems.Columns.Add("itemc");
listitems.Columns.Add("itemd");
// Add new items
listitems.Rows.Add(itema, itemb, itemc, itemd);
return listitems;
}
private void button1_Click(object sender, EventArgs e)
{
// add to data grid
dataGridView1.DataSource = additems("New text", "Almonds", "Butter", "Salt");
}
I wanted the above code to create new data grid. And it works fine for single data.. but for multiple data how can i achieve such heights?
I have a new variable (not using any database). Whenever button1 is clicked this variable needs to be loaded to data table so that it can instantly add to datagridview1.
I need some concepts...
well, you could change the method sig to take a new parameter for the datatable ...
if that's null, create a new table like you do now ... if it's not null, simply add a new row to that existing table
//quick and dirty example
static DataTable additems(string itema, string itemb, string itemc, string itemd, DataTable foo)
{
DataTable listitems = foo;
if(foo == null)
{
listitems = new DataTable();
listitems.Columns.Add("itema");
listitems.Columns.Add("itemb");
listitems.Columns.Add("itemc");
listitems.Columns.Add("itemd");
}
// Add new items
listitems.Rows.Add(itema, itemb, itemc, itemd);
return listitems;
}
private void button1_Click(object sender, EventArgs e)
{
// add to data grid
dataGridView1.DataSource = additems("New text", "Almonds", "Butter", "Salt", (DataTable)dataGridView1.DataSource);
}
you also might want to think about storing that datatable in a private field, instead of using (DataTable)dataGridView1.DataSource
, but the question wasn't about good coding style ;)
精彩评论