如何在数据网格视图中将焦点设置为新添加的行或行的末尾?

时间:2013-10-31 13:01:03

标签: c# winforms datagridview

我有一个datagridview和一个Add按钮。每次我向datagridview添加数据时,我都希望它将焦点设置到新添加的行或其末尾。也许是因为我的datagridview总是在它的末尾添加/插入数据。

以下是我的代码:(我在事件SelectionChanged中有一些错误。)

Boolean flag_cell_edited;
int currentRow;
int currentColumn;

private void ListView_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
    flag_cell_edited = true;
    currentColumn = e.ColumnIndex;
    currentRow = e.RowIndex;
}

private void ListView_SelectionChanged(object sender, EventArgs e)
{
    if(flag_cell_edited)
    {
        ListView.CurrentCell = ListView(currentColumn, currentRow);
        flag_cell_edited = false;
    }
}

添加行

static DataGridView _dg;
SqlDataAdapter _da;

public void Add()
    {
        sc.Open();

        try
        {
            using (cmd = new SqlCommand(@"INSERT INTO TableVotersInfo (Education, idnum, FirstName, MiddleName, LastName, SchoolYear, ControlNum, VResult)
                                    SELECT @ed, @idnum, @firstname, @middlename, @lastname, @schoolyear, @controlnum, 'Not Voted' 
                                    WHERE @idNum NOT IN (SELECT idNum FROM TableVotersInfo);", sc))
            {
                Param();

                var rowsAffected = cmd.ExecuteNonQuery();
                if (rowsAffected == 0)
                {
                    MessageBox.Show("ID number already exist!");
                    FAddVoters._checkID = checkID;
                    FAddVoters._cleardata = "0";
                }
                else
                {
                    MessageBox.Show("Data Stored Successfully!");
                    FAddVoters._cleardata = cleardata;
                    FAddVoters._checkID = "0";
                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
        finally
        {
            sc.Close();
        }
    }


public void retList()
{
    sc.Open();
    cmd = new SqlCommand("SELECT * FROM TableVotersInfo", sc);

    try
    {
        _da = new SqlDataAdapter();
        _da.SelectCommand = cmd;
        DataTable _dt = new DataTable();
        _da.Fill(_dt);
        BindingSource bs = new BindingSource();
        bs.DataSource = _dt;
        _dg.DataSource = bs;
        _da.Update(_dt);
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
    finally
    {
        sc.Close();
    }
}

1 个答案:

答案 0 :(得分:1)

您可以使用RowsAdded这样的事件:

DataGridViewRow lastSelected;
//RowsAdded event handler for your dataGridView1
private void dataGridView1_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e){
    if (dataGridView1.CurrentCell != null) 
       dataGridView1.CurrentCell.OwningRow.Selected = false;
    if (lastSelected != null) lastSelected.Selected = false;
    lastSelected = dataGridView1.Rows[e.RowIndex];
    lastSelected.Selected = true;
}

注意:该代码仅用于单个添加行。如果添加了多行,则将选择其中的第一行。