我有一个包含 3 个 TextBox、一个 comboBox 和一个 DatagridView 的表单,其中客户端为 TextBox1 或 TextBox2 或 TextBox3 中的文本的一部分或为了更多规范,他可以选择 comboBox1 的一个项目结果显示在 dataGridView(numeo_cpte,intitulé_cpte) 中。我的问题是我在 dataGridview 中得到结果的 northig 和 int 转换错误 => 输入数据的格式不正确
这是我的代码:
private void button5_Click(object sender, EventArgs e)
{
int a =Convert.ToInt32(textBox1.Text); //format of enetered data is incorrect
String b = textBox3.Text;
String c = comboBox1.SelectedItem.ToString();
String d = textBox4.Text;
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
req="select numero_cpte,intitulé_cpte from compte where numero_cpte='"+a+"' OR intitulé_cpte like '%"+b+"%' OR type_cpte='"+c+"' OR index_full_text_cpte like'%"+d+"%';";
SqlCommand sql = new SqlCommand(req,connection);
int o = sql.ExecuteNonQuery();
MessageBox.Show(o + " succès");
dr = new SqlDataAdapter(req, connection);
dr.Fill(ds, "compte");
compteDataGridView.DataSource = ds.Tables["compte"];
connection.Close();
我添加了一行
int n=0;
int a =int.TryParse(textBox1.Text,out n)?n:0;
这就是我得到的,没有错误,但我没有在 datagridView 中显示任何结果:
我做“成功”只是为了测试 再次感谢您的帮助
最佳答案
如果字符串未格式化为整数,则会发生此错误。 例如:
Convert.ToInt32("1") // returns 1
Convert.ToInt32("1.1") // is not in a recognizable format
您应该先尝试使用正则表达式来应用某些格式,或者使用 try/catch 语句。如果您仍然遇到问题,能否在此位置设置调试断点并向我们提供 textbox1.Text 提供的违规字符串的副本?
希望这对您有所帮助!
关于c# - int 的格式不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24201024/