You must Sign In to post a response.
  • Category: Windows

    Need validate Single Char Only in Datagridview

    Hai all,
    I want Enter Single Char only In Datagridview Cell.How to Validate like That?
    here my Sample Code.

    this.dataGridView1.EditingControlShowing += new DataGridViewEditingControlShowingEventHandler(dataGridView1_EditingControlShowing;


    void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
    {
    e.Control.KeyPress += new KeyPressEventHandler(Control_KeyPress);
    }



    void Control_KeyPress(object sender, KeyPressEventArgs e)
    {
    if (e.KeyChar.ToString() != "N" && e.KeyChar.ToString() != "y")
    {
    e.Handled = true;
    }

    }
  • #695080
    if (e.KeyChar.ToString() != "N" || e.KeyChar.ToString() != "y")

  • #695081
    Selvaraj, this is not Valid Code

  • #695111
    Hai Srinivasan,
    First of all set the max length of the textbox which is inside the DataGrid to 1 so that user will not be able to enter more than 1 characters.
    After that you can validate it in the key-press event for the textbox. To validate the textbox, first you need to get the column and row in which the textbox exists. After getting the textbox, you can use your code which should probably work.
    You can use the below code snippet for 'your reference:

    private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
    {
    if (this.dataGridView1.CurrentCell.ColumnIndex == 2)
    {
    if (!this.eventHookedUp)
    {
    e.Control.KeyDown += this.Cell_KeyDown;
    this.eventHookedUp = true;
    }
    }
    else
    {
    e.Control.KeyDown -= this.Cell_KeyDown;
    this.eventHookedUp = false;
    }
    }
    private void Cell_KeyDown(object sender, KeyEventArgs e)
    {
    if (e.KeyChar.ToString() != "N" || e.KeyChar.ToString() != "y" || e.KeyChar.ToString() != "n" || e.KeyChar.ToString() != "Y")
    e.Handled = true;
    else
    e.Handled = false;
    }

    Hope it will be helpful to you.

    Regards,
    Pawan Awasthi(DNS MVM)
    +91 8123489140 (whatsApp), +60 14365 1476(Malaysia)
    pawansoftit@gmail.com


  • This thread is locked for new responses. Please post your comments and questions as a separate thread.
    If required, refer to the URL of this page in your new post.