【问题标题】:Previous button not working for DataGridView C#上一个按钮不适用于 DataGridView C#
【发布时间】:2018-07-26 10:27:40
【问题描述】:

如何修复前一个按钮在 dataGridView 行中向后移动? 下一个按钮正在工作。 它什么也不做。 我不知道如何解决这个问题。有任何想法吗?我会很感激的。

这是我的代码:

int nRow;

private void Form1_Load
{
    nRow = DataGridView2.CurrentCell.RowIndex;
}

private void PreviousData_Click
{
    if (row>=0)
    {
        if (row!=0)
        {
            DataGridView2.Rows[row].Selected = false;
            DataGridView2.Rows[--row].Selected = true;
        }
        else
        {
            MessageBox.Show("Need More Data!");
        }
    }
}

int row;

private void DataGridView2_CellClick
{
    if (DataGridView2.SelectedRows.Count != -1)
    {
        row = DataGridView2.CurrentRow.Index;
    }
}

【问题讨论】:

  • 为什么不单步调试代码?
  • 对我来说,这看起来不像是按钮单击事件处理程序。你是如何将事件绑定到点击的?在代码中还是通过设计器?谢谢
  • @Wheels73 这段代码中没有任何东西是可编译的
  • @Chris - 建议您将帖子修改为可编译的代码。如果您的“下一个”按钮正常工作,但您尚未发布,只需对上一个按钮执行相同操作即可。

标签: c# datagridview


【解决方案1】:

将以下两个事件分别绑定到您的previousnext 按钮,它就可以完成这项工作。

private void PreviousData_Click(object sender, EventArgs e)
{
    var currentRow = DataGridView2.CurrentCell.RowIndex;

    if (currentRow == 0)
        return;
    else
        currentRow--;

    DataGridView2.ClearSelection();
    DataGridView2.CurrentCell = DataGridView2.Rows[currentRow].Cells[0];
    DataGridView2.Rows[currentRow].Selected = true;
}

private void NextData_Click(object sender, EventArgs e)
{
    var currentRow = DataGridView2.CurrentCell.RowIndex;

    if (currentRow == DataGridView2.RowCount - 1)
        return;
    else
        currentRow++;

    DataGridView2.ClearSelection();
    DataGridView2.CurrentCell = DataGridView2.Rows[currentRow].Cells[0];
    DataGridView2.Rows[currentRow].Selected = true;
}

【讨论】:

  • 运行良好!我应该修改什么以获得最后一行点击?
  • @Chris 你说的get the last row for click是什么意思?
  • 喜欢,跳到最后插入的行
  • 我做了一些修改,运行良好:) int currentRow = DataGridView2.Rows.Count - 1; DataGridView2.ClearSelection(); DataGridView2.CurrentCell = DataGridView2.Rows[currentRow].Cells[0]; DataGridView2.Rows[currentRow].Selected = true;
猜你喜欢
  • 1970-01-01
  • 2016-08-07
  • 2022-06-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-05
相关资源
最近更新 更多