问题
I created a DataGridView with some columns. The order columns only allow users enter int number. It throws the FormatException when I enter "j" (for example) and I try to add try catch to fix the problem, but it looks does not work..
private void Form1_Load(object sender, EventArgs e)
{
try{
this.sourceTable = new DataTable(TableName);
this.sourceTable.Columns.Add(new DataColumn(OrderCol, Type.GetType("System.Int32")));
dataGridView1.DataSource = sourceTable;
}catch(FormatException){
MessageBox.Show("Please enter a number");
}
}
回答1:
Try this: I've added an event for column changing where I can check the input when it's submitted.
private DataColumn dataColumn;
private void Form1_Load(object sender, EventArgs e)
{
this.sourceTable = new DataTable(TableName);
dataColumn = new DataColumn(OrderCol);
this.sourceTable.Columns.Add(dataColumn);
sourceTable.ColumnChanged += sourceTable_ColumnChanged; // Eventhandler for column changes
dataGridView1.DataSource = sourceTable;
}
void sourceTable_ColumnChanged(object sender, DataColumnChangeEventArgs e)
{
try
{
int i = Convert.ToInt32(e.ProposedValue);
}
catch (FormatException)
{
MessageBox.Show("Please enter a number");
}
}
回答2:
Handle DataGridView.CellValidating event:
private void CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
try
{
// get current cell
var cell = ((DataGridView)sender).Rows[e.RowIndex].Cells[e.ColumnIndex];
// check new value. i need any number >= 5
var c0 = 0;
if (e.FormattedValue == null || !Int32.TryParse(e.FormattedValue.ToString(), out c0) || c0 < 5)
{
// bad value inserted
// e.FormattedValue - is new value
// cell.Value - contains 'old' value
// choose any:
cell.Value = cell.Value; // this way we return 'old' value
e.Cancel = true; // this way we make user not leave the cell until he pastes the value we expect
}
}
catch (Exception ex)
{
}
}
来源:https://stackoverflow.com/questions/19582852/c-sharp-formatexception-in-datagridview