3

我创建了一个带有一些列的 DataGridView。order 列只允许用户输入 int number。当我输入“j”(例如)时它会抛出 FormatException 并且我尝试添加 try catch 来解决问题,但它看起来不起作用..

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

2 回答 2

4

试试这个:我添加了一个列更​​改事件,我可以在提交时检查输入。

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");
            }
        }
于 2013-10-25T07:13:38.573 回答
0

处理 DataGridView.CellValidating 事件:

    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)
        {
        }
    }
于 2015-06-30T20:31:59.167 回答