2010-03-07 65 views

回答

16

您可以通過以下方式訪問任何DGV細胞:

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

但烏蘇盟友最好使用數據綁定:通過DataSource屬性將DGV綁定到數據源(DataTable,集合...),並且只能在數據源本身上工作。該DataGridView會自動反映所做的更改,並在DataGridView所做的更改將數據源

+0

即使我們可以編輯和添加值並將其保存到數據庫 – SurajSing 2013-03-26 09:43:58

11

這是完美的代碼,但它不能添加新行上反映:

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

我很確定索引在第二個示例中不固定。 – quantum 2012-10-27 01:48:55

+0

所以它不完美,因爲它不能添加新行? :) – 2016-04-01 03:26:19

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

希望這有助於! :)

相關問題