Reputation: 933
i have a datagrid with the following cell formatting
datagrid.rows[0].cells[0].Value =1;
datagrid.rows[0].cells[0].Style.Format ="#k";
this works fine and the output will be 1k, however when the user edit the cell value example to 2 then cell formatting will not take effect?
question is how can i retain the cell formatting after user edit?
thanks
Upvotes: 2
Views: 3453
Reputation: 47978
I guess you are not working with an underlying datasource. You are inserting DataGridViewRows
manually into the DataGridView
.
If you were using a datasource, if the column datatype was numeric, the styling will work in both edit and readonly modes.
In your case, you need to handle the CellFormatting
event of the DataGridView
and set the format of your cell there:
void dataGridView1_CellFormatting(object sender,
DataGridViewCellFormattingEventArgs e)
{
if (e.ColumnIndex == 0 && e.RowIndex == 0)
{
// if the underlying type is int
int value;
if(e.Value != null && int.TryParse(e.Value.ToString(), out value))
{
e.Value = value.ToString("#k");
/*** OR ***
e.Value = value;
e.CellStyle.Format = "#k";
*/
}
}
}
Upvotes: 3