C#中出现FormatException中的DataGridView [英] C# FormatException in DataGridView

查看:137
本文介绍了C#中出现FormatException中的DataGridView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创造了一些列的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(请输入一个数字);
            }
        }
 

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

这篇关于C#中出现FormatException中的DataGridView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆