首页 > 解决方案 > c#在DataGridview中显示选定的行

问题描述

我的 datagridview 填充了多行数据,我可以在我的 datagridview 中选择多行,然后想要更新 datagridview 以显示选定的行。

在这种情况下,如果它已经在屏幕上,我可以显示选定的行(简而言之:如果它被选中,则需要将 datagridview 向上滚动到选定的行或结束行)

do
{
    for (int j = 0; j <= stringToHighlight.Length; j++)
    {
        if (ColID > 15)
        {
            rowID++;
            ColID = 0;
        }
        if (stringToHighlight[j].ToString().ToLower() == dataGridView1.Rows[rowID].Cells[ColID].Value.ToString().ToLower())
        {
            GridView_Binary.Rows[rowID].Cells[ColID].Selected = true;
            dataGridView1.Rows[rowID].Cells[ColID].Selected = true;
            ColID++;
        }
        else
        {
            GridView_Binary.ClearSelection();
            dataGridView1.ClearSelection();
            break;
        }

        if (j == stringToHighlight.Length - 1)
        {
            ISNext = false;

            return true;
        }
    }
    ColID++;
}
while (ISNext);

标签: c#winforms

解决方案


要滚动到选定的行,请使用:

dataGridView1.FirstDisplayedScrollingRowIndex = dataGridView1.SelectedRows[0].Index;

如果您希望所有检查代码如下所示:

//Checking if data grid view have rows
if(dataGridView1.Rows.Count > 0)
{
    //Checking if anything is selected
    if(dataGridView1.SelectedRows.Count > 0)
    {
        //Selecting first of all selected rows in datagridview
        dataGridView1.FirstDisplayedScrollingRowIndex = dataGridView1.SelectedRows[0].Index;
    }
    else
    {
        //Selecting last row in data grid view
        dataGridView1.FirstDisplayedScrollingRowIndex = (dataGridView1.Rows.Count - 1);
    }
}

推荐阅读