簡體   English   中英

C#將值插入DataGridView

[英]C# Insert value into 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);
        }

我嘗試調試以遵循周期中的索引是正確的,盡管結果有誤。

因為您在新行中插入數據,所以新行總是添加到所有行中。

要在添加行之后從第一行更改數據,您必須更改以下代碼:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM