设置DataGridView单元格值并添加一个新行 [英] Set DataGridView cell value and add a new row
问题描述
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;
}
}
这样做,但是我想要一个新行当单元格值被设置时被添加。当我手动编辑单元格时,会发生这种情况,该行处于编辑状态,下面添加一个新行。当我以编程方式设置单元格值时,我想同样会发生。
当我的表单首先显示DataGridView为空,唯一的行显示为(* sign - IsNewRow为true)。当我手动编辑该行中的单元格时,将进入编辑状态(铅笔符号),并添加一个新的空行。当我使用上面的代码时,这不会发生。行仍然是IsNewRow(* sign),并且没有添加新行。
使用此代码,您可以执行所需的操作。我用同样的原因:
myGrid.NotifyCurrentCellDirty(true);
此答案的来源:
以编程方式使新行脏,并插入新的在DataGridView 之后的行
I have a DataGridView with two columns. 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. 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. 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). When I manually edit a cell in that row it goes into edit state (pencil sign) and a new empty row is added. This doesn't happen when I use the above code. The row remains as IsNewRow (* sign) and a new row is not added.
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单元格值并添加一个新行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!