Click here to Skip to main content
15,891,204 members
Articles / Database Development / SQL Server
Article

Handling Keyboard Events of DataGrid Cells

Rate me:
Please Sign up or sign in to vote.
3.62/5 (6 votes)
9 Mar 2006CPOL 60.2K   22   4
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:

C#
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:

C#
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:

C#
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:

C#
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

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead
Pakistan Pakistan
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Suggestion[My vote of 1] Handling Keyboard Events of DataGrid Cells Pin
munirabbas15-May-12 2:09
munirabbas15-May-12 2:09 
GeneralHandling Key-Board Events of DataGrid on client side Pin
24891287-Aug-06 18:08
24891287-Aug-06 18:08 
GeneralThank you for figuring this out Pin
robregan17-Mar-06 10:57
robregan17-Mar-06 10:57 
GeneralRe: Thank you for figuring this out Pin
Asher Syed19-Mar-06 19:02
Asher Syed19-Mar-06 19:02 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.