C#中出现FormatException中的DataGridViewFormatException、DataGridView

由网友(北棠)分享简介:我创造了一些列的DataGridView。顺序列只允许用户输入整型数字。它抛出出现FormatException当我输入J(例如),我尝试添加尝试捕捉来解决这个问题,但看起来不起作用。私人无效Form1_Load的(对象发件人,EventArgs的){尝试{this.sourceTable =新的DataTable(...

我创造了一些列的DataGridView。顺序列只允许用户输入整型数字。它抛出出现FormatException当我输入J(例如),我尝试添加尝试捕捉来解决这个问题,但看起来不起作用。

 私人无效Form1_Load的(对象发件人,EventArgs的)
{
  尝试{
     this.sourceTable =新的DataTable(表名);
     this.sourceTable.Columns.Add(新的DataColumn(OrderCol,Type.GetType(System.Int32的)));

     dataGridView1.DataSource = sourceTable;
  }赶上(出现FormatException){
     的MessageBox.show(请输入一个数字);
  }
}
 

解决方案

试试这个: 我已经添加了一个事件列变化,我可以确认输入时,它的提交。

 私人的DataColumn的DataColumn;
        私人无效Form1_Load的(对象发件人,EventArgs的)
        {

                this.sourceTable =新的DataTable(表名);
                的DataColumn =新的DataColumn(OrderCol);
                this.sourceTable.Columns.Add(的DataColumn);
                sourceTable.ColumnChanged + = sourceTable_ColumnChanged; //事件处理程序的列变化

                dataGridView1.DataSource = sourceTable;

        }

        无效sourceTable_ColumnChanged(对象发件人,DataColumnChangeEventArgs E)
        {
            尝试
            {
                INT I = Convert.ToInt32(e.ProposedValue);

            }
            赶上(出现FormatException)
            {
                的MessageBox.show(请输入一个数字);
            }
        }
 

System.FormatException 输入字符串的格式不正确

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

阅读全文

相关推荐

最新文章