1
我有一個DataGridView
4列(隱藏第3列)。 DataGridView
已準備好用於用戶輸入時(我添加了一行並設置AllowUserToAddRows=false)
。當用戶按Enter
然後下一個單元格是集中和可編輯。第三列後按Enter
然後應插入一個新行通過KeyDown向DataGridView添加新行
對於加入新行我有已插入的數據寫回datatable
因爲DataGridView
已經是數據綁定
當我嘗試訪問中,我插入它返回我始終爲零的一些值的第一行:
如何訪問第一行?謝謝!
代碼Datatable
:
dtKasse.Columns.Add("Nummer");
dtKasse.Columns.Add("Unternummer");
dtKasse.Columns.Add("Betrag");
dtKasse.Columns.Add("Datum");
dtKasse.Rows.Add("", "", "", DateTime.Now.ToShortTimeString());
gv_Input.AllowUserToAddRows = false;
gv_Input.DataSource = dtKasse;
DataGridViewCell cell = gv_Input.Rows[0].Cells[0];
gv_Input.CurrentCell = cell;
gv_Input.BeginEdit(true);
隱藏第三列:
private void gv_Input_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
gv_Input.Columns[3].Visible = false;
}
手柄按下Enter
:
private void gv_Input_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyData == Keys.Enter)
{
int col = gv_Input.CurrentCell.ColumnIndex;
int row = gv_Input.CurrentCell.RowIndex;
if (col < 2)
{
col++;
}
else
{
col = 0;
row++;
}
if (row == gv_Input.RowCount)
{
dtKasse.Clear();
foreach (DataGridViewRow dgr in gv_Input.Rows)
{
dtKasse.Rows.Add(dgr.Cells[0].Value, dgr.Cells[1].Value, dgr.Cells[2].Value, dgr.Cells[3].Value);
}
DataRow dr = dtKasse.NewRow();
dtKasse.Rows.Add(dr);
gv_Input.DataSource = dtKasse;
}
DataGridViewCell cell = gv_Input.Rows[row].Cells[col];
gv_Input.CurrentCell = cell;
gv_Input.BeginEdit(true);
}
}