问题
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?

回答1:
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");
}
}
}
回答2:
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();
}
}
回答3:
You can Set you Format String using CellStyle Builder an set the Custom format to # mm
How to do it :
- Right click on Grid, then Properties
- In the property window, click the button that will popup up the Edit Columns Dialog
- Select the cell you want to format
- On the right side of the Edit Columns Dialog select the DefaultCellStyle property
- Click the DefaultCellStyle property, then the CellStyleBuilder dialog will open
- Here you have the format property, this will give you the Format String Dialog
- Set the Custom property to #mm you will see the preview at the bottom
- Click OK ... till you are back to your Grid...
来源:https://stackoverflow.com/questions/11340292/set-display-format-for-winform-datagridview