C#将值插入DataGridView

时间:2016-03-02 16:03:19

标签: c# winforms datagridview

我遇到DataGridView的问题,正如您在此处看到的那样,当我在单元格中输入值( LOL )实际上只是它出现在最后一行

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 个答案:

答案 0 :(得分:1)

因为您在新行中插入数据而新行总是添加到最后一行。

对于添加行后第一行的更改数据,您必须更改此代码:

dataGridNoteLavaggio.Rows[dataGridNoteLavaggio.NewRowIndex].Cells

dataGridNoteLavaggio.Rows[index].Cells

indexRows.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";
                    }
                }
            }
        }
    }
}