2
votes

I am new to WinForms development, currently I am maintaining an application developed in .Net 2.0

In the application, I have grid with column called Length which displays the value with unit. I have used CellFormatting event to format the cell value, otherwise it is just number.

But when user start editing I wouldn't want unit to be displayed, user should be allowed enter only numbers.

Is there any straight forward way to do it? Events or Properties to be set on the grid?

enter image description here

3

3 Answers

1
votes

You should set the unit in the event DataGridView_CellFormatting

void DataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    if (e.ColumnIndex == 1)
    {
        int value;
        if(e.Value != null && int.TryParse(e.Value.ToString(), out value))
        {
            e.Value = value.ToString("#mm");
        }
    }
}
1
votes

You should handle the EditingControlShowing event to change the current cell format.

    private void dataGridView1_EditingControlShowing(object sender, 
                               DataGridViewEditingControlShowingEventArgs e)
    {
        if (dataGridView1.CurrentCell.ColumnIndex == 1)
        {
            e.CellStyle.Format = "#";
            e.Control.Text = dataGridView1.CurrentCell.Value.ToString();
        }
    } 
1
votes

You can Set you Format String using CellStyle Builder an set the Custom format to # mm

How to do it :

  1. Right click on Grid, then Properties
  2. In the property window, click the button that will popup up the Edit Columns Dialog
  3. Select the cell you want to format
  4. On the right side of the Edit Columns Dialog select the DefaultCellStyle property
  5. Click the DefaultCellStyle property, then the CellStyleBuilder dialog will open
  6. Here you have the format property, this will give you the Format String Dialog
  7. Set the Custom property to #mm you will see the preview at the bottom
  8. Click OK ... till you are back to your Grid...