Click here to Skip to main content
Click here to Skip to main content

Handling Keyboard Events of DataGrid Cells

By , 9 Mar 2006
 

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

License

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

About the Author

Asher Syed
Technical Lead
Pakistan Pakistan
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
Suggestion[My vote of 1] Handling Keyboard Events of DataGrid Cellsmembermunirabbas15 May '12 - 2:09 
GeneralHandling Key-Board Events of DataGrid on client sidememberNigam Samir7 Aug '06 - 18:08 
GeneralThank you for figuring this outmemberzarkon17 Mar '06 - 10:57 
GeneralRe: Thank you for figuring this outmemberAsher Syed19 Mar '06 - 19:02 

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

Permalink | Advertise | Privacy | Mobile
Web01 | 2.6.130523.1 | Last Updated 9 Mar 2006
Article Copyright 2006 by Asher Syed
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid