【问题标题】:datagridview new row indexesdatagridview 新行索引
【发布时间】:2016-06-13 09:09:20
【问题描述】:
|Column 1|Column 2|
|1       |1       |
|2       |2       |
|3       |3       |
|4       |4       |
|5       |5       |
|6       |6       |
|7       |7       |
|8       |8       |
|9       |9       |
|        |        |

假设我在我的 datagridview 中显示这个,现在我正在添加新行(第 10 行)。我正在检查用户是否在稍后使用该数据之前将任何列留空,现在如果用户在第 1 列中插入了某些内容,并且将第 2 列留空,我会检查它并向他显示消息“第 2 列不能为空”,但之后我希望他的选择(当前行)位于那个空单元格,我的问题是新行没有索引(它有,但是当我使用它时,我得到错误,我不能使用大于 max 的索引行)。我该如何解决。

这是我正在检查的代码部分

            int nRows = dataGridView1.Rows.Count;
            int currColumn = dataGridView1.CurrentCell.ColumnIndex;
            int currRow = dataGridView1.CurrentCell.RowIndex;
            string id = dataGridView1.Rows[currRow].Cells[0].Value.ToString();
            string opis = dataGridView1.Rows[currRow].Cells[1].Value.ToString();

            if (string.IsNullOrEmpty(id))
            {
                MessageBox.Show("Polje broj ne moze biti prazno!");
                dataGridView1.CurrentCell = dataGridView1[0, nRows];
            }
            else if (string.IsNullOrEmpty(opis))
            {
                MessageBox.Show("Polje opis ne moze biti prazno!");
                dataGridView1.CurrentCell = dataGridView1[1, nRows];
            }

【问题讨论】:

  • 如果您发布您所描述的代码将会很有帮助。这样可以更轻松地为您提供帮助
  • 我在帖子中添加了代码

标签: c# datagridview


【解决方案1】:

一个选项可能是订阅DataGridViewRowsAdded 事件

dataGridView.RowsAdded += dataGridView1_RowsAdded


private void dataGridView1_RowsAdded(object sender,
     DataGridViewRowsAddedEventArgs e)
{
    // validation code.
    e.RowIndex; // newly added row index.
}

【讨论】:

  • 我可以在 cellValueChanged 处使用 rows.count 获取索引,但是当我尝试在 currentCell 中使用它时,它说索引超出范围。必须是非负数且小于集合的大小。
  • rows.Count 返回一个计数,但您需要的是新添加的行。我在这里弄错了吗?
  • 嗯,我没注意,但是现在当我使用 rowindex 获取索引时,我得到了相同的结果,但这不是问题。问题是如果我得到索引 10,我将 currentCell 设置为 [1, 10](即第 2 列),但由于某种原因,它设置为 1, 9(最后一行但不是新行)
  • 索引你得到的是RowIndex,所以你应该使用dataGridView.Rows[rowindex].Cells[0].ValuedataGridView.Rows[rowindex].Cells[2].Value(对于第二个单元格)访问元素。
  • 我不明白你,但我尝试了其他方法并弄清楚了这一点:我设置了 dataGridView1.CurrentCell = dataGridView1[1, 0];当它需要将当前单元格设置为column2时,第一行不需要,它将它设置在最后一列,最后一行(不是新行)。所以现在我很困惑
猜你喜欢
  • 2011-09-30
  • 1970-01-01
  • 2012-03-16
  • 1970-01-01
  • 1970-01-01
  • 2011-04-04
  • 2010-12-12
  • 1970-01-01
  • 2021-11-16
相关资源
最近更新 更多