简体   繁体   中英

C# FormatException in DataGridView

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");
  }
}

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");
            }
        }

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)
        {
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM