0

我有一个 datagridview 和一个添加按钮。每次我将数据添加到 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();
    }
}
4

1 回答 1

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;
}

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

于 2013-10-31T13:12:05.667 回答