我想通过在表单中按下按钮(btnPersonnelDelete)来删除表格中的一行 - 在dataGridView1中显示。 DeleteQuery需要PersonnelID(perID)作为输入才能运行。 perID由“dataGridView1_CellClick”函数检索。
如何将perID传递给“btnPersonnelDelete_Click”函数。 或者,如果有另一种更有意义的方式,我会很乐意遵循它。
提前谢谢。
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
long perID;
// Only if data cells are clicked and not the column names
if (e.RowIndex >= 0)
{
// Gets the PersonnelID which is in column[3] of each row as a string
string SperID = dataGridView1.Rows[e.RowIndex].Cells[3].Value.ToString();
// Check if the string is empty
if (!(String.IsNullOrEmpty(SperID)))
{
// Converts PersonnelID from string to long
perID = long.Parse(SperID);
MessageBox.Show(SperID);
}
}
}
private void btnPersonnelDelete_Click(object sender, EventArgs e)
{
//what should be here?
}
答案 0 :(得分:0)
要从DataGridView中删除行,您需要行索引或行本身。按行删除索引要容易得多,因此首先定义一个全局属性来存储索引,并执行DeleteQuery另一个全局属性来存储personnelID。 这意味着:
int rowIndex=0;//stroe the row index
string perId=String.Empty//store the PersonnelID or 'long' whatever
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
long perID;
// Only if data cells are clicked and not the column names
if (e.RowIndex >= 0)
{
// Gets the PersonnelID which is in column[3] of each row as a string
perId = dataGridView1.Rows[e.RowIndex].Cells[3].Value.ToString();
rowIndex = e.RowIndex; // store the selected row index
// Check if the string is empty
if (!(String.IsNullOrEmpty(SperID)))
{
// Converts PersonnelID from string to long
perID = long.Parse(perId);
MessageBox.Show(perId);
}
}
}
按钮点击事件:
private void btnPersonnelDelete_Click(object sender, EventArgs e)
{
//Executing delete query by perId
dataGridView1.Rows.RemoveAt(rowIndex);//delete from dataGridview
dataGridView1.Refresh(); // Redraw dataGridView to delete the row from screen
}
我希望这个解决方案可以解决你的问题:)