如何向DataGridView单元格中插入值?

16

我有一个 DataGridView(它保存了任何的 DataBase

我想要插入任何值到任何单元格中(并且这个值会保存在数据库中)

如何用 C# 实现它

提前感谢

5个回答

22

您可以按照以下方式访问任何DGV单元格:

dataGridView1.Rows[rowIndex].Cells[columnIndex].Value = value;

通常最好使用数据绑定:通过 DataSource 属性将 DGV 绑定到数据源(DataTable, collection...),仅对数据源本身进行操作。 DataGridView 将自动反映更改,并且在 DataGridView 上进行的更改将反映在数据源上。


我们可以在哪个偶数上进行编辑和添加值,并将其保存到数据库中? - SurajSing

19

这是完美的代码,但它无法添加新行:

dataGridView1.Rows[rowIndex].Cells[columnIndex].Value = value;

但是这段代码可以插入新的行:

var index = this.dataGridView1.Rows.Add();
this.dataGridView1.Rows[index].Cells[1].Value = "1";
this.dataGridView1.Rows[index].Cells[2].Value = "Baqar";

1
我非常确定第二个例子中的索引并不是固定的。 - quantum

3

出于某些原因,我无法将数字(以字符串格式)添加到DataGridView中。但这对我有用,希望能帮助到其他人!

//dataGridView1.Rows[RowCount].Cells[0].Value = FEString3;//This was not adding Stringed Numbers like "1","2","3"....
DataGridViewCell NewCell = new DataGridViewTextBoxCell();//Create New Cell
NewCell.Value = FEString3;//Set Cell Value
DataGridViewRow NewRow = new DataGridViewRow();//Create New Row
NewRow.Cells.Add(NewCell);//Add Cell to Row
dataGridView1.Rows.Add(NewRow);//Add Row To Datagrid

1
int index= datagridview.rows.add();
datagridview.rows[index].cells[1].value=1;
datagridview.rows[index].cells[2].value="a";
datagridview.rows[index].cells[3].value="b";

希望这能帮到你! :)

非常感谢!这样做容易多了! - Bogdan Doicin

0

如果你想通过一个按钮将数据添加到数据库中,你可以使用这个函数。希望它能帮到你。

// dgvBill is name of DataGridView

string StrQuery;
try
{
    using (SqlConnection conn = new SqlConnection(ConnectingString))
    {
        using (SqlCommand comm = new SqlCommand())
        {
            comm.Connection = conn;
            conn.Open();
            for (int i = 0; i < dgvBill.Rows.Count; i++) 
            {
                StrQuery = @"INSERT INTO tblBillDetails (IdBill, productID, quantity, price,  total) VALUES ('" + IdBillVar+ "','" + dgvBill.Rows[i].Cells[0].Value + "', '" + dgvBill.Rows[i].Cells[4].Value + "', '" + dgvBill.Rows[i].Cells[3].Value + "', '" + dgvBill.Rows[i].Cells[2].Value + "');";
                comm.CommandText = StrQuery;
                comm.ExecuteNonQuery();         
             }
         }
     }
 }
 catch (Exception err)
 {
     MessageBox.Show(err.Message  , "Error !");
 }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接