简体   繁体   English

设置 DataGridView 单元格值并添加新行

[英]Set DataGridView cell value and add a new row

I have a DataGridView with two columns.我有一个包含两列的 DataGridView。 When a cell in the first column is clicked, an OpenFileDialog is shown and when I select a file, the cell in the second column value is set to the selected file name.单击第一列中的单元格时,将显示一个 OpenFileDialog,并且当我 select 一个文件时,第二列中的单元格值设置为所选文件名。 Here is the code:这是代码:

private void dataGridView1_CellContentClick(
    object sender, DataGridViewCellEventArgs e)
{
    if (e.ColumnIndex == 0)
    {
        SelectFile(e.RowIndex);
    }
}

private void SelectFile(int rowIndex)
{
    if (openFileDialog.ShowDialog() == DialogResult.OK)
    {
        dataGridView1.Rows[rowIndex].Cells[1].Value =
            openFileDialog.FileName;
    }
}

This works, but I would like a new row to be added when the cell value is set.这可行,但我希望在设置单元格值时添加一个新行。 This happens when I edit the cell manually, the row gets in 'edit' state and a new row is added below.当我手动编辑单元格时会发生这种情况,该行进入“编辑”state 并在下面添加一个新行。 I would like the same to happen when I set the cell value programmatically.当我以编程方式设置单元格值时,我希望发生同样的情况。

[edit] [编辑]

When my form is first shown the DataGridView is empty and the only row is shown is the one with (* sign - IsNewRow is true).当我的表单第一次显示时,DataGridView 是空的,并且唯一显示的行是带有(* 符号 - IsNewRow 为真)的行。 When I manually edit a cell in that row it goes into edit state (pencil sign) and a new empty row is added.当我手动编辑该行中的一个单元格时,它会进入编辑 state(铅笔符号)并添加一个新的空行。 This doesn't happen when I use the above code.当我使用上面的代码时,这不会发生。 The row remains as IsNewRow (* sign) and a new row is not added.该行保持为 IsNewRow(* 符号)并且不添加新行。

在此处输入图像描述在此处输入图像描述

I ran into the same problem, too.我也遇到了同样的问题。 I did something like the following, it just works..!我做了类似以下的事情,它只是工作..! (.Net framework 4.5) (.Net 框架 4.5)

// Set value for some cell, assuming rowIndex refer to the new row.
dateGridView1.Rows[rowIndex].Cells[1].Value = "Some Value";

// Then simply do this:
dataGridView1.BeginEdit(true);
dataGridView1.EndEdit();

With this code you can do what you want to do.使用此代码,您可以做您想做的事情。 I Used it for the same reason:我出于同样的原因使用它:

myGrid.NotifyCurrentCellDirty(true);

Source of this answer: Make new row dirty programmatically and insert a new row after it in DataGridView此答案的来源: 以编程方式使新行变脏并在 DataGridView 中插入新行

I ran into the same problem.我遇到了同样的问题。 Didn't figure out a more elegant solution but thought it might be helpful to provide some code:没有找到更优雅的解决方案,但认为提供一些代码可能会有所帮助:

//...
    DialogResult dr = ofd.ShowDialog();
    if (dr == DialogResult.OK)
        {
            DataGridViewRow curRow = cell.DataGridView.Rows[cell.RowIndex];
            // check if the current row is the new row
            if (curRow.IsNewRow)
            {
                // if yes, add a new one
                int newRowIdx = cell.DataGridView.Rows.Add();
                DataGridViewRow newRow = cell.DataGridView.Rows[newRowIdx];
                DataGridViewCell newCell = newRow.Cells[cell.ColumnIndex];
                // check if the new one is _not_ the new row (this is the unexpected behavior mentioned in the questions comments)
                if (!newRow.IsNewRow)
                    newCell.Value = ofd.FileName;
                else if (!curRow.IsNewRow)
                    cell.Value = ofd.FileName;
            }
            else {
                cell.Value = ofd.FileName;
            }
        }

I ran into this and solved it in a different way.我遇到了这个问题并以不同的方式解决了它。

Basically the user clicks a button on the DataGridView , it opens a dialog which asks questions, then fills the row out.基本上,用户单击DataGridView上的一个按钮,它会打开一个询问问题的对话框,然后填写该行。 Just for the fun of it, I fixed it by using SendKeys to get the row in edit mode instead of new mode.只是为了它的乐趣,我通过使用SendKeys在编辑模式而不是新模式下获取行来修复它。 You don't have to use SendKeys to fill out the entire row, just one cell is enough to make it work.您不必使用SendKeys来填写整行,只需一个单元格即可使其工作。

Two important things to note.需要注意的两个重要事项。 First the datagridview needs to have multiselect off, or you need to unselect the current cell(s).首先,datagridview 需要关闭多选,或者您需要取消选择当前单元格。 Second, you need the defaultvaluesneeded event to work and fill the grid with sane data.其次,您需要 defaultvaluesneeded 事件来工作并用健全的数据填充网格。

myRow.Cells("dgvStockNumber").Selected = True
OrderDetailDataGridView.BeginEdit(True)
SendKeys.Send("{Backspace}")
SendKeys.Send(scp.MyStockCard.StockNumber)
Application.DoEvents()
OrderDetailDataGridView.EndEdit()
myRow.Cells("dgvChooseStockCard").Selected = True
OrderDetailDataGridView.CommitEdit(DataGridViewDataErrorContexts.Commit)

There are better ways to go about this, but this is easy lol. go 有更好的方法来解决这个问题,但这很容易哈哈。

If it's on load you will need to add the new row first, then to give its cell a value do something like this.如果它正在加载,您将需要先添加新行,然后为它的单元格指定一个值,执行类似的操作。

When I was trying to fill certain columns of a Datagrid with certain columns of some Datatable and retrieving its data from a SQL database, I used this:当我试图用某些 Datatable 的某些列填充 Datagrid 的某些列并从 SQL 数据库中检索其数据时,我使用了这个:

       if (dtbl.Rows.Count > 0)
        {
            for (int i = 0; i < dtbl.Rows.Count; i++)
            {
                    // adding a row each time it loops in and find a row in the dtbl
                    dataGridView1.Rows.Add();

                    dataGridView1.Rows[i].Cells[0].Value = dtbl.Rows[i][0].ToString();
                    dataGridView1.Rows[i].Cells[1].Value = dtbl.Rows[i][1].ToString();
                    dataGridView1.Rows[i].Cells[2].Value = dtbl.Rows[i][2].ToString();
            }
            dataGridView1.ReadOnly = true;
            dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
        }  

I searched for the solution how I can insert a new row and How to set the individual values of the cells inside it like Excel.我搜索了如何插入新行以及如何设置其中单元格的单个值的解决方案,例如 Excel。 I solved with following code:我用以下代码解决了:

dataGridView1.ReadOnly = false; //Before you modify it, it should be set to false!

dataGridView1.Rows.Add(); //This inserts first row, index is "0"
dataGridView1.Rows[0].Cells[0].Value = "this is 0,0!"; //This line will set the right hand string to the very first cell of your datagridview.

Note: 1. Previously I have designed the columns in design mode.注意: 1. 以前我在设计模式下设计了列。 2. I have set the row header visibility to false from property of the datagridview. 2. 我已从 datagridview 的属性中将行 header 可见性设置为 false。

Hope this might help you.希望这可以帮助你。

It's not real clear what you're trying to do, but you can add new rows to a DataGridView like this:目前尚不清楚您要做什么,但是您可以像这样向 DataGridView 添加新行:

dataGridView1.Rows.Add()

the.Add() method is overloaded, so check which Add method is the one you want in visual studio. the.Add() 方法已重载,因此请检查哪个Add方法是您在 Visual Studio 中想要的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM