繁体   English   中英

如何将值插入到 DataGridView 单元格中?

[英]how to insert value into DataGridView Cell?

我有DataGridView (持有任何DataBase

我想将任何值插入任何单元格(并且该值将保存在数据库中)

怎么做(在 C# 中)

提前致谢

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

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

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

这是完美的代码,但它不能添加新行:

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";

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

希望这有帮助! :)

如果您想将数据添加到数据库中,您可以使用此功能,通过一个按钮。 我希望它会有所帮助。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM