Microsoft Communities

Welcome to WindowsClient.net | Sign in | Join

Here are some frequently asked questions about Windows Forms and their answers.

Windows Forms FAQs

How do I put up a confirmation dialog when the user tries to delete a row in the DataGrid by clicking on the row header and pressing the Delete key?

You can handle this by subclassing your grid and overriding either PreProcessMessage or ProcessDialogKey. The code below assumes your datasource is a dataview. If it is not, you could just remove that check

[C#]

public class CustomDataGrid : DataGrid
{
  private const int WM_KEYDOWN = 0x100;

  public override bool PreProcessMessage( ref Message msg )
  {
    Keys keyCode = (Keys) (int) msg.WParam & Keys.KeyCode;
    if ( msg.Msg == WM_KEYDOWN
      && keyCode == Keys.Delete
      && ( (DataView) DataSource ).AllowDelete )
    {
      if ( MessageBox.Show( "Delete this row?", "Confirm delete",
          MessageBoxButtons.YesNo ) == DialogResult.No )
        return true;
    }
    return base.PreProcessMessage( ref msg );
  }
}

[Visual Basic]

Public Class CustomDataGrid
  Inherits DataGrid

  Private Const WM_KEYDOWN = &H100

  Public Overrides Function PreProcessMessage(ByRef msg As Message) As Boolean
    Dim keyCode As Keys = CType((msg.WParam.ToInt32 And Keys.KeyCode), Keys)
    If msg.Msg = WM_KEYDOWN And keyCode = Keys.Delete Then
      If MessageBox.Show("Delete this row?", "Confirm delete", _
          MessageBoxButtons.YesNo) = DialogResult.No Then
        Return True
      End If
    End If
    Return MyBase.PreProcessMessage(msg)
  End Function
End Class

George Shepherd, Syncfusion, and Erik Johansen



Page view counter