c# - int 的格式不正确

标签 c# sql-server database datagrid sql-injection

我有一个包含 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 中显示任何结果:

enter image description here

我做“成功”只是为了测试 再次感谢您的帮助

最佳答案

如果字符串未格式化为整数,则会发生此错误。 例如:

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/

相关文章:

c# - 将 SQL Server 数据导出到 CSV 文件

sql - 如何在 MS-Access 中检索最后一个自动递增的值,如 SQL Server 中的@@Identity

php - 无法插入数据库(steamauth)

c# - MediaComposition.RenderToFileAsync 因许多静态图像而崩溃

mysql - 在我的案例中,如何从第一个表中找到第二个表中丢失的行?

php - 测验的数据库结构是什么样的?

excel - excel如何统计某个字段出现在特定 'week'的次数

C# 不重复的不可变和可变类型

C# 数学,碰撞检测,xna

c# - RX : Stateful transform of sequence, 例如指数移动平均线