尝试在数据网格视图中使用新记录创建的按钮上创建单击时事件



尝试在 dataGridView 中为每个记录创建的按钮上单击侦听器

OleDbConnection connection = new OleDbConnection();
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "SELECT * FROM vc";
OleDbDataAdapter da = new OleDbDataAdapter(command);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
DataGridViewButtonColumn col = new DataGridViewButtonColumn();
col.UseColumnTextForButtonValue = true; 
col.Text = "Folder";
col.Name = "MyButton";
dataGridView1.Columns.Add(col);

您需要查看 DataGridView.CellClick Event

  1. 尝试以下代码添加按钮,

    // Add a button column. 
    DataGridViewButtonColumn buttonColumn = 
        new DataGridViewButtonColumn();
    buttonColumn.HeaderText = "";
    buttonColumn.Name = "MyButton";
    buttonColumn.Text = "Folder"; 
    buttonColumn.UseColumnTextForButtonValue = true;
    
  2. CellClick处理程序

    // Add a CellClick handler to handle clicks in the button column.
    dataGridView1.CellClick +=
        new DataGridViewCellEventHandler(dataGridView1_CellClick);
    
  3. 是的,dataGridView1_CellClick本身就可以让你的东西对抗咔嗒声。需要看的一件事是,

您必须查找单击的按钮单元格,否则每次单击单元格内容都会触发它。

    void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
    {
        // Ignore clicks that are not on button cells. 
        if (e.RowIndex < 0 || e.ColumnIndex !=
            dataGridView1.Columns["myButton"].Index) return;
       ...... 
       you stuff....
    }

最新更新