我有一个 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();
}
}