我遇到DataGridView
的问题,正如您在此处看到的那样,当我在单元格中输入值( LOL )实际上只是它出现在最后一行
代码:
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);
}
我尝试使用调试来跟踪循环中的索引是否正确但是尽管结果是错误的。
答案 0 :(得分:1)
因为您在新行中插入数据而新行总是添加到最后一行。
对于添加行后第一行的更改数据,您必须更改此代码:
dataGridNoteLavaggio.Rows[dataGridNoteLavaggio.NewRowIndex].Cells
到
dataGridNoteLavaggio.Rows[index].Cells
和index
从Rows.Add()
方法设置。你的代码应该是这样的:
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";
}
}
}
}
}
}