C# Adding rows in DataGridView
I currently have the following codes and I would like to add a new row into the DataGridView when buttonX1 is clicked, how can i do this?
private void Form1_Load(object sender, EventArgs e)
{
string query = "SELECT * FROM Bill";
OleDbDataAdapter dAdapter = new OleDbDataAdapter(query, DBconn);
OleDbCommandBuilder cBuilder = new OleDbCommandBuilder(dAdapter);
DataTable dTable = new DataTable();
dAdapter.Fill(dTable);
//BindingSource to sync DataTable and DataGridView
BindingSource bSource = new BindingSource();
//开发者_如何学Cset the BindingSource DataSource
bSource.DataSource = dTable;
//set the DataGridView DataSource
dataGridViewX1.DataSource = bSource;
dAdapter.Update(dTable);
}
private void buttonX1_Click(object sender, EventArgs e)
{
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT INTO Bill (Item, Quantity, Price) VALUES ('Soft Drink', 1, 1)";
cmd.Connection = DBconn;
DBconn.Open();
cmd.ExecuteNonQuery();
DBconn.Close();
}
private void Select()
{
string query = "SELECT * FROM Bill";
OleDbDataAdapter dAdapter = new OleDbDataAdapter(query, DBconn);
OleDbCommandBuilder cBuilder = new OleDbCommandBuilder(dAdapter);
DataTable dTable = new DataTable();
dAdapter.Fill(dTable);
//BindingSource to sync DataTable and DataGridView
BindingSource bSource = new BindingSource();
//set the BindingSource DataSource
bSource.DataSource = dTable;
//set the DataGridView DataSource
dataGridViewX1.DataSource = bSource;
dAdapter.Update(dTable);
}
private void buttonX1_Click(object sender, EventArgs e)
{
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT INTO Bill (Item, Quantity, Price) VALUES ('Soft Drink', 1, 1)";
cmd.Connection = DBconn;
DBconn.Open();
cmd.ExecuteNonQuery();
DBconn.Close();
//call the Select function
Select();
}
The way you pose you question suggests that you don't understand how it's supposed to work.
When you do the SqlDataAdapter.Fill, the DataTable is filled with a copy of the data from the database table. The DataGridView is an object that displays that data to the user.
When you want to add a row, you should add it in the DataTable dTable, but getting a new row:
(This goes in the Button click event).
DataRow dr = dTable.NewRow()
Putting your data in it:
dr[0] = something; dr[1] = somethng; etc.
Then add the row to the table
dTable.Rows.Add(dr) ;
When you have changed the data in the Table, you have to save the data back to the database using the DataSource.
精彩评论