DataGridView导航到下一行
我有一个C#winforms应用程序,我正在尝试使用一个按钮,在选择一个之后将选择datagridview中的下一行。
我到目前为止的代码是:
private void button4_Click(object sender, EventArgs e) { try { Int32 selectedRowCount = dataGridView1.Rows.GetRowCount(DataGridViewElementStates.Selected); // index out of range on this line dataGridView1.Rows[dataGridView1.SelectedRows[selectedRowCount].Index].Selected = true; dataGridView1.FirstDisplayedScrollingRowIndex = selectedRowCount + 1; } catch (Exception ex) { return; }
但是在运行它时会引发exception。 任何人都可以指出我可能出错的地方。 抛出的错误是: Index is out of range
试试这个:
int nRow; private void Form1_Load(object sender, EventArgs e) { nRow = dataGridView1.CurrentCell.RowIndex; } private void button1_Click(object sender, EventArgs e) { if (nRow < dataGridView1.RowCount ) { dataGridView1.Rows[nRow].Selected = false; dataGridView1.Rows[++nRow].Selected = true; } }
它在这里:
dataGridView1.SelectedRows[selectedRowCount]
如果您有3个选定的行,则selectedRowCount = 3并且有三行索引:0,1,2。
您正在尝试访问不存在的#3。
首先,将daatgridview的“Multiselect”属性设置为false。
int currentRow = dataGridView1.SelectedRows[0].Index; if (currentRow < dataGridView1.RowCount) { dataGridView1.Rows[++currentRow].Selected = true; }
它将选择datagridview中的下一行。
读取值单元格或列的此示例是datagridview的编号4
int courow = dataGridView1.RowCount-1; for (int i=0; i < courow; i++) { MessageBox.Show(dataGridView1.Rows[i].Cells[4].Value.ToString()); }
选择行和单元以获得更好的解决方案 此解决方案在DataGridView上移动行指示符。
private void _GotoNext(object sender, EventArgs e) { int currentRow = DataGridView1.SelectedRows[0].Index; if (currentRow < DataGridView1.RowCount - 1) { DataGridView1.Rows[++currentRow].Cells[0].Selected = true; } } private void _GotoPrev(object sender, EventArgs e) { int currentRow = DataGridView1.SelectedRows[0].Index; if (currentRow > 0) { DataGridView1.Rows[--currentRow].Cells[0].Selected = true; } }
dgv_PhotoList.Rows[dgv_PhotoList.CurrentRow.Index+1].Selected = true;
- ASP.NET | 表单身份validation| 获取所有登录用户(所有用户列表或计数)
- c ++中的枚举类-replacement- in c#
- WPF / Silverlight程序员:MVVM是否过度杀伤?
- Visual Studio 2015 SQL Server数据工具缺少“添加表”选项
- 如何使用opencv从字节显示video?
- x:将ViewModel方法绑定到DataTemplate中的Event
- DataGridComboBoxColumn用于不同行的不同ItemsSource
- 使用.NET检查逗号分隔列表中字符串的最佳方法?
- 在“查找所有引用”中显示方法名称 – C#Visual Studio