如何将DataGridView_CellClick函数中单元格的内容传递到C#中的button_Click函数
本文关键字:函数 Click 中的 button DataGridView CellClick 单元格 | 更新日期: 2023-09-27 18:29:41
我想通过按下表单中的按钮(btnPersonelDelete)来删除表中的一行,该行显示在dataGridView1中。DeleteQuery需要PersonnelID(perID)作为输入才能运行。perID由"dataGridView1_CellClick"函数检索。
如何将perID传递给"btnPersoneDelete_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?
}
要从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
}
我希望这个解决方案能解决您的问题:)