WinForms DataGridView中的OnClick事件

eom*_*off 3 c# datagridview buttonclick winforms

我在WinForms中使用DataGridView,通过这段代码,我将它分配给列和值

dataGrid.DataSource = sourceObject;
Run Code Online (Sandbox Code Playgroud)

只有通过这一行将所有列和值放入网格中.如何处理特定行或字段的onClick事件.我想编辑网格中的特定项目,但我找不到任何方法从事件方法发送项目的ID.

有类DataGridViewEventHandler,我不明白?

我还尝试手动添加列作为按钮,但我没有找到方法来为它分配动作方法onClick.

Asa*_*sad 5

您无法在DataGridView中找到单元格的"OnClick"事件,因为它不存在.查看为Cell Manipulation和Events提供的DataGridView事件的 MSDN页面

以下是来自MSDN的一些示例,关于您可能使用的事件

示例CellMouseClick事件和处理程序

   private void DataGridView1_CellMouseClick(Object sender, DataGridViewCellMouseEventArgs e)    {

    System.Text.StringBuilder cellInformation = new System.Text.StringBuilder();
    cellInformation .AppendFormat("{0} = {1}", "ColumnIndex", e.ColumnIndex );
    cellInformation .AppendLine();
    cellInformation .AppendFormat("{0} = {1}", "RowIndex", e.RowIndex );
    cellInformation .AppendLine();
    MessageBox.Show(cellInformation.ToString(), "CellMouseClick Event" );
}
Run Code Online (Sandbox Code Playgroud)

示例CellClick事件和处理程序

private void dataGridView1_CellClick(object sender,
    DataGridViewCellEventArgs e)
{

    if (turn.Text.Equals(gameOverString)) { return; }

    DataGridViewImageCell cell = (DataGridViewImageCell)
        dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex];

    if (cell.Value == Play)
    {
        // PlaySomething()
    }
    else if (cell.Value == Sing)
    {
        // SingSomeThing();
    }
    else 
    {
     MessagBox.Show("Please Choose Another Value");
    }
}
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助