簡體   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