gpt4 book ai didi

DataGridView 中的 C# FormatException

转载 作者:行者123 更新时间:2023-11-30 20:53:54 26 4
gpt4 key购买 nike

我创建了一个包含一些列的 DataGridView。顺序栏只允许用户输入整数。当我输入“j”(例如)并尝试添加 try catch 来解决问题时它抛出 FormatException,但它看起来不起作用..

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

最佳答案

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

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

关于DataGridView 中的 C# FormatException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19582852/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com