65.9K
CodeProject is changing. Read more.
Home

Handling Keyboard Events of DataGrid Cells

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.62/5 (6 votes)

Mar 9, 2006

CPOL
viewsIcon

60968

Handling Key-Down and similar events for DataGridCells in a DataGrid

Introduction

This is my first contribution to The Code Project. Recently, while trying to trap KeyDown and KeyPress events for a cell in a DataGrid proved far beyond difficult as KeyPress, KeyDown and similar events are only provided for the DataGrid.

Sample Code for Handling KeyDown Event for a DataGridCell

Create a TableStyle for the DataGrid:

private void CreateTableStyle()
{
    try
    {
        DataGridTableStyle ts = new DataGridTableStyle();
        ts.HeaderForeColor = Color.Black;  
        ts.HeaderFont = new Font("Verdana", (float)8.25);   
        ts.MappingName = this.dt.TableName;
            
        DataGridColumnStyle cs;
        DataGridTextBoxColumn tbc;
    
        foreach( DataRow dr in this.columns.Rows)
        {
            if ( dr["ColType"].ToString() == "System.Boolean")
            {
                cs = new DataGridBoolColumn();
                ((DataGridBoolColumn)cs).AllowNull = false;
            }
            else 
            {
                cs = new DataGridTextBoxColumn();
                tbc = (DataGridTextBoxColumn) cs;
                tbc.TextBox.KeyDown += new KeyEventHandler(TextBox_KeyDown);
            }
        
            cs.HeaderText = dr["ColName"].ToString();
            cs.MappingName = dr["ColName"].ToString();
            cs.Width = Convert.ToInt32(dr["ColWidth"].ToString());
                                                
            if (dr["ReadOnly"].ToString() == "true")
            {
                cs.ReadOnly = true;
            }

            switch( dr["ColAlign"].ToString().ToUpper())
            {
                case "C":
                    cs.Alignment = HorizontalAlignment.Center;
                    break;
                case "L":
                    cs.Alignment = HorizontalAlignment.Left;
                    break;
                case "R":
                    cs.Alignment = HorizontalAlignment.Right; 
                    break;                            
            }
                        
            ts.HeaderFont = new System.Drawing.Font("Verdana", 8.25F);
            ts.HeaderBackColor = Color.Gainsboro; 
            ts.HeaderForeColor = Color.Black;
            ts.SelectionBackColor  = Color.Silver;                    
            ts.AllowSorting = true;    
            ts.GridColumnStyles.Add(cs);                    
        }

        this.dg.TableStyles.Clear();
        this.dg.TableStyles.Add(ts);
        this.dg.DataSource = this.dt;
    }
    catch ( Exception e )
    {
        throw e;
    }
}

Add the code in the handler of the KeyDown event of the TextBox:

private void TextBox_KeyDown(object sender, KeyEventArgs e)
{
    try
    {
        if ((e.KeyCode >= Keys.A) && (e.KeyCode <= Keys.Z))
        {
            this.SearchExpression += (char) e.KeyValue;
            this.SetFilter(this.GetCurrentColumnName());                    
        }
        else
        {
            if (e.KeyCode == Keys.Delete || e.KeyCode == Keys.Back || 
            e.KeyCode == Keys.Space)
            {
                this.SearchExpression = string.Empty;
                this.ViewRecords.RowFilter = string.Empty;
                this.dg.SetDataBinding(this.dt,"");
            }            
        }
    }
    catch(Exception ex)
    {
        MessageBox.Show(ex.Message.ToString());
    }
}

Get the current column name of the DataGrid cell:

private string GetCurrentColumnName()
{
    try
    {
        int colNo;
    
        if (this.dt != null)
        {
            colNo = this.dg.CurrentCell.ColumnNumber;
            return this.dg.TableStyles[0].GridColumnStyles[colNo].MappingName.ToString();
        }
        else
        {
            return string.Empty;
        }
    }
    catch(Exception ex)
    {
        MessageBox.Show(ex.Message.ToString());
        return string.Empty;
    }            
}

Set the RowFilter on a DataView declared in Form or UserControl:

private void SetFilter(string ColumnName)
{            
    try
    {
        this.ViewRecords = new DataView(this.dt);
    
        this.ViewRecords.AllowNew = false;
        this.ViewRecords.AllowEdit = false;
        this.ViewRecords.AllowDelete = false;

        if (ColumnName != string.Empty)
        {
            this.ViewRecords.RowFilter = "[" + ColumnName + "] " + 
                "LIKE '" +  this.SearchExpression + "' + " + "'%'";
            this.dg.SetDataBinding(this.ViewRecords,"");
        }
    }
    catch(Exception ex)
    {
        MessageBox.Show(ex.Message.ToString());
    }
}

Points of Interest

This article shows how to trap and handle KeyBoard events for cells in a DataGrid.

History

  • 03-09-2006: First version uploaded