Thank you everuone for responding. I tried a modified version of the code sample by Henry, here:
private void generalLedgerEntryDataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
if (e.ColumnIndex == generalLedgerEntryDataGridView.Columns["DebitAmount"].Index)
string enteredValue = e.Value.ToString();
Decimal valueHolder = 0;
Decimal.TryParse(enteredValue, out valueHolder);
e.Value = -Math.Abs(valueHolder);
e.FormattingApplied = true;
However, when i run the application, and try to open the form, it gives the error "NullReferenceException was unhandled by user code"
Earlier, I had tried this at the Dataset level:
First i override begin edit thus:
public override void BeginInit()
this.ColumnChanging += GeneralLedgerEntryDataTable_RowChanging;
Then added this event handler:
private void GeneralLedgerEntryDataTable_RowChanging(object sender, DataColumnChangeEventArgs e)
if (e.Column.ColumnName == "DebitAmount")
if (Convert.ToDecimal(e.ProposedValue) == null)
else if (Convert.ToDecimal(e.ProposedValue) != 0)
Decimal negetive = 0;
string value = e.ProposedValue.ToString();
Decimal.TryParse(value, out negetive);
e.ProposedValue = -negetive;
This works fine if i am adding only records that have values in the DebitAmount column. And saves just fine to the database. But as soon as i add a row with empty value in the DebitAmount field, when i try to save to the database, it throws the following exception:InvalidCastException. Object Cannot be cast from DBNull to other type.
I guess what i need is to check if the DebitAmount column is null, and if so, to skip it right? But then i dont know the code to do it!
Please Someone help me with this.
NOTE: I will prefer perfoming this conversion at the Dataset level in the BLL (Its a three layer application) instead of doing so at the UI (datagridview). So i will prefer option two above.
Thanks all for the help.