Click here to Skip to main content
15,879,535 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have a datagridview with five columns. all the columns must accept the letters beside one column. I want my second column to accept only one number or two numbers with no spaces and it must no even allow the users to type other characters than the numbers only.

What i have tried. the problem is that i don't know how i can point it to my gridcolumn which is my index 2

C#
private void Gridview_Output_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {

            e.Control.KeyPress += new KeyPressEventHandler(Gridview_Output_KeyPress);

        }


C#
private void Gridview_Output_KeyPress(object sender, KeyPressEventArgs e)
      {
          if (!char.IsControl(e.KeyChar)
          && !char.IsDigit(e.KeyChar)
          && e.KeyChar != '.')
              {
                  e.Handled = true;
              }
      }
Posted
Comments
Adrian Vaideanu 10-Mar-15 6:53am    
Are the DataGridView cells editable or you just bind to a model?
How are you binding to the data grid cell ?
What exactly do you mean by "point it to my gridcolumn which is my index 2"?

1 solution

I manage to find a solution using this method

C#
private void Gridview_Output_CellEndEdit_1(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
pre lang="cs">int RowIndex = e.RowIndex;
               int columnIndex = e.ColumnIndex;
               if (e.ColumnIndex == 2)
               {
                   bool validation = true;
                   if (Gridview_Output.Rows[RowIndex].Cells[columnIndex].Value != null && Gridview_Output.Rows[RowIndex].Cells[columnIndex].Value.ToString().Trim() != "")
                   {
                       string DataToValidate = Gridview_Output.Rows[RowIndex].Cells[columnIndex].Value.ToString();
                       foreach (char c in DataToValidate)
                       {
                           if (!char.IsDigit(c))
                           {
                               validation = false;
                               break;
                           }
                       }
                       if (validation == false)
                       {
                           MessageBox.Show("Font must be numbers only", "Error Message", MessageBoxButtons.OKCancel,MessageBoxIcon.Warning);
                           Gridview_Output.Rows[RowIndex].Cells[columnIndex].Value = &quot;&quot;;</pre>
 
Share this answer
 

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900