C# FormatException in DataGridView

风流意气都作罢 提交于 2019-12-11 02:34:50

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!