首页 > 解决方案 > 新列上的单元格值不会改变

问题描述

无论我做什么,我都无法使用以下方法设置单元格的值:

row.Cells["columnName"].Value = "some text";

我正在使用 Datatable 作为其源填充 DatagridView。但是对于某个列,我希望用户能够使用下拉列表来更改值。所以我隐藏了由数据源生成的列,然后创建一个新的组合框列,添加项目然后从隐藏列传输值。

  private void ShotsDGV()
        {
            // if there is data, clear the DGV and let the data create its own columns
            if (shotsData.Rows.Count > 0)
            {
                shotsDataGrid.Columns.Clear();
                
                // set new column as a dropdown column
                DataGridViewComboBoxColumn newSequenceColumn = new DataGridViewComboBoxColumn();
                
                // Assign the data from the datatable to the DGV
                shotsDataGrid.DataSource = shotsData;

                //Hide the Auto Generated Column
                //shotsDataGrid.Columns["Sequence"].Visible = false;

                // Set the Header Text of the New Column            
                newSequenceColumn.HeaderText = "Sequence";

                // Set the Name of the New Column
                newSequenceColumn.Name = "newSequenceHeader";

                //get the Items from the other dataTable and add all of the options for the Dropdown
                for (int i = 0; i < seqData.Rows.Count; i++)
                {
                    newSequenceColumn.Items.Add(seqData.Rows[i].ItemArray[0].ToString());
                }

                // add this new column to the DGV
                shotsDataGrid.Columns.Add(newSequenceColumn);

                //set the new column to be in the right position
                shotsDataGrid.Columns["newSequenceHeader"].DisplayIndex = 2;

                // copy data from original column
                foreach (DataGridViewRow row in shotsDataGrid.Rows)
                {
                    row.Cells["newSequenceHeader"].Value = row.Cells["Sequence"].Value;
                    Console.WriteLine(row.Cells["newSequenceHeader"].Value + " - Tada! ");

                }       
            }
        }

我没有收到任何错误,并且我直接在控制台写入后说该值设置...但它只是没有在窗口中的实际单元格中添加值...它作为添加了我的选项的下拉列表工作,但在我从下拉菜单中手动选择之前,单元格是空白的。我还可以使用相同的方法在任何 OTHER 列中设置任何其他单元格,它工作正常,但是我创建的这个新列不会被设置。

奇怪的是,我已经使用完全相同的技术从另一个 DataGridView 复制了这段代码,并且该代码运行良好。我不明白为什么这个以完全相同的方式创建的新列不允许我在其中设置任何值。

标签: c#winformsdatatabledatagridview

解决方案


推荐阅读