如何将值插入DataGridView Cell?

我有DataGridView (包含任何DataBase

我想在任何Cell中插入任何值(并且该值将保存在DataBase上)

怎么做(在C#中)

提前致谢

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

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

但通常最好使用数据绑定:通过DataSource属性将DGV绑定到数据源( DataTable ,collection …),并且只对数据源本身起作用。 DataGridView将自动反映更改, DataGridView上所做的更改将反映在数据源上

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

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

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

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

由于某些原因,我无法将数字(以字符串格式)添加到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 

如果要使用按钮将数据添加到数据库中,可以使用此function。 我希望它会有所帮助。

 // 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 !"); } 
 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"; 

希望这个帮助! 🙂