问题描述
我在运行时创建了一个datagridview。 gridview使用来自access数据库的数据填充。我还在gridview中创建了一个Button列,其中包含gridview中每行的删除按钮。事件处理程序是DataGridView.CellContentClick
现在,当我单击删除按钮时,消息框会要求确认。当确认是的问题被删除,否则它必须什么都不做。
代码工作正常但问题出现在代码第一次运行时。
第二次它自动调用事件处理程序DataGridView.CellContentClick而不按下删除按钮。
我无法理清问题。请帮助。
这是代码:
I have created a datagridview at run time. The gridview is populated with data from access database. I have also created a Button Column in the gridview that contains a delete button for each row in the gridview. The event handler is the "DataGridView.CellContentClick"
Now when I click the delete button, message box asks for confirmation. When confirmed for yes question is deleted else it must do nothing.
The code works fine but the problem comes when the code has run for the first time.
Second time it automatically calls the the event handler "DataGridView.CellContentClick" without pressing the delete button.
I can not sort out the problem. Please Help.
Here is the code:
void dataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
int count = 0;
var senderGrid = (DataGridView)sender;
if (senderGrid.Columns[e.ColumnIndex] is DataGridViewButtonColumn)
{
if (e.ColumnIndex == dataGridView.Columns["DeleteButton"].Index)
{
if (dataGridView.Rows[e.RowIndex].IsNewRow != true)
{
int qno;
qno = e.RowIndex + 1;
DialogResult choice = MessageBox.Show("Are you sure want to delete this Question?\nDeleted question can not be reovered.", "Delet Question", MessageBoxButtons.YesNo);
//Delete the question from the table.
if (choice == DialogResult.Yes)
{
dataGridView.Rows.RemoveAt(qno - 1);
queryDelete = "delete from " + subject + " where QueNo=" + qno + "and SetNo=" + setNo;
try
{
connection.Open();
command = new OleDbCommand(queryDelete, connection);
command.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
connection.Close();
MessageBox.Show("Question Deleted.", "Deleted");
}
else
{
/* Do Nothing */
}
}
}
}
}
推荐答案
using(DialogResult choice = MessageBox.Show("Are you sure want to delete this Question?\nDeleted question can not be reovered.", "Delet Question", MessageBoxButtons.YesNo))
{
//Delete the question from the table.
if (choice == DialogResult.Yes)
{
dataGridView.Rows.RemoveAt(qno - 1);
queryDelete = "delete from " + subject + " where QueNo="
+ qno + "and SetNo=" + setNo;
try
{
connection.Open();
command = new OleDbCommand(queryDelete, connection);
command.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
connection.Close();
MessageBox.Show("Question Deleted.", "Deleted");
}
else
{
/* Do Nothing */
}
}
这篇关于datagridview按钮自动获得焦点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!