[英]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? 我目前有以下代码,当单击buttonX1时,我想在DataGridView中添加新行,我该怎么做?
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();
//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();
}
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. 当您执行SqlDataAdapter.Fill时,DataTable中填充了数据库表中数据的副本。 The DataGridView is an object that displays that data to the user. DataGridView是一个向用户显示该数据的对象。
When you want to add a row, you should add it in the DataTable dTable, but getting a new row: 当您要添加行时,应将其添加到DataTable dTable中,但要获得新行:
(This goes in the Button click event). (这在Button单击事件中进行)。
DataRow dr = dTable.NewRow() DataRow dr = dTable.NewRow()
Putting your data in it: 将数据放入其中:
dr[0] = something; dr [0] =某物; dr[1] = somethng; dr [1] = somethng; etc. 等等
Then add the row to the table 然后将行添加到表中
dTable.Rows.Add(dr) ; 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. 更改表中的数据后,必须使用数据源将数据保存回数据库。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.