2016-03-02 80 views
1

我有一個問題,一個DataGridView,因爲你可以到這裏看看,當我在細胞內的輸入值(LOL)實際上是隻出現在最後一行C#插入值到DataGridView的

DataGridView

代碼:

private void CaricaNoteLavaggio() 
{ 
    using (DatabaseConnection db = new DatabaseConnection()) 
    { 
     const string query = "" // My query 
     using (MySqlDataReader reader = db.ExecuteReader(query)) 
     { 
      if (reader.HasRows) 
      { 
       while (reader.Read()) 
       { 
        DataGridViewRow row = new DataGridViewRow(); 
        dataGridNoteLavaggio.Rows.Add(row); 

        foreach (DataGridViewCell cell in dataGridNoteLavaggio.Rows[dataGridNoteLavaggio.NewRowIndex].Cells) 
        { 
         cell.Value = "LOL"; 
        } 
       } 
      } 
     } 
    } 
} 

創建動態使用這一段代碼的DataGridView的(列如果該可能是有用的)

 DataGridViewTextBoxColumn txtId = new DataGridViewTextBoxColumn(); 
     txtId.HeaderText = "ID"; 
     txtId.Name = "id"; 
     txtId.AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells; 
     txtId.Visible = false; 

     dataGridNoteLavaggio.Columns.Add(txtId); 

     // Function that returns the list of languages (EN, FR, ES, etc. ...) 
     List<string> lingue = DatabaseFunctions.GetLingue(); 
     foreach (var lingua in lingue) 
     { 
      DataGridViewTextBoxColumn txtDesc = new DataGridViewTextBoxColumn(); 
      txtDesc.HeaderText = lingua; 
      txtDesc.Name = lingua; 
      txtDesc.AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells; 

      dataGridNoteLavaggio.Columns.Add(txtDesc); 
     } 

我嘗試了與調試遵循循環中的指標是正確的,但儘管結果是錯誤的。

回答

1

因爲您在新行中插入數據,並且新行總是添加到最後一行。

從第一行添加行必須更改此代碼後變化的數據:

dataGridNoteLavaggio.Rows[dataGridNoteLavaggio.NewRowIndex].Cells 

dataGridNoteLavaggio.Rows[index].Cells 

Rows.Add()方法index集。你的代碼應該是這樣的:

private void CaricaNoteLavaggio() 
{ 
    using (DatabaseConnection db = new DatabaseConnection()) 
    { 
     const string query = "" // My query 
     using (MySqlDataReader reader = db.ExecuteReader(query)) 
     { 
      if (reader.HasRows) 
      { 
       while (reader.Read()) 
       { 
        DataGridViewRow row = new DataGridViewRow(); 
        var index = dataGridNoteLavaggio.Rows.Add(row); 

        foreach (DataGridViewCell cell in dataGridNoteLavaggio.Rows[index].Cells) 
        { 
         cell.Value = "LOL"; 
        } 
       } 
      } 
     } 
    } 
}