C#Datagridview选中行

时间:2014-12-05 20:54:49

标签: c# datagridview selectedindex

我有一个datagridview,我已经实现了搜索功能。通过在datagridview处于焦点时输入字符,将选择具有字符的网格的第一行。

我用:

dtgView[index].Selected = true;
dtgView.FirstDisplayedScrollingRowIndex = index;

该行被选中,但是当我按向上或向下箭头从所选行向上或向下导航时,datagridview从数据网格中的行索引0开始而不是新选择的行?

以下是OP's原始代码/方法

private void dtgView_KeyUp(object sender, KeyEventArgs e)
{
    if (e.KeyValue >= 65 && e.KeyValue <= 90 )
    {
        searchStrings += e.KeyCode;
        for (int i = 0; i < dtgView.RowCount; i++)
        {
            if (dtgView.Rows[i].Cells[0].Value.ToString().
                Substring(0, searchStrings.Length) == searchStrings)
            {
                dtgView.ClearSelection();
                dtgView.FirstDisplayedScrollingRowIndex = i;
                dtgView.Rows[i].Selected = true;
                dtgView.Rows[i].Cells[0].Selected = true;
                break;
            }
        }
    }

}

1 个答案:

答案 0 :(得分:0)

这是我在dtg上的Key_up事件:

private void dtgView_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyValue >= 65 && e.KeyValue <= 90 )
            {
                searchStrings += e.KeyCode;
                for (int i = 0; i < dtgView.RowCount; i++)
                {
                    if (dtgView.Rows[i].Cells[0].Value.ToString().
                        Substring(0, searchStrings.Length) == searchStrings)
                    {

                        dtgView.ClearSelection();
                        dtgView.FirstDisplayedScrollingRowIndex = i;
                        dtgView.Rows[i].Selected = true;
                        dtgView.Rows[i].Cells[0].Selected = true;

                        break;
                    }
                }
            }

        }