如何解决此错误(类型'System.FormatException'的未处理异常 [英] How to solve this error(an unhandled exception of type 'System.FormatException'

查看:71
本文介绍了如何解决此错误(类型'System.FormatException'的未处理异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

hii,每个人

如何解决此错误(类型'System.FormatException'的未处理异常......)



在按钮搜索时,放入字符会给我这个错误。





 da.SelectCommand = new SqlCommand(   select * from tblcontacts其中id类似于 + Int32.Parse(textBox3。 Text ),cs); 
dt.Clear();
da.Fill(dt);

dataGridView1.DataSource = dt;

解决方案

无需转换为整数即可转换它再次回到一个字符串。只需使用:



  new  SqlCommand(  select * from tblcontacts其中id如 + textBox3.Text,cs)





但是你应该学习参数化查询和SQL注入攻击。这可以让您了解数据库中的主要黑客行为。


试试这个





如Ron说,请注意 SQL_injection [ ^ ]



 string query = string.Format(< span class =code-string>  select * from tblcontacts where id like'{0}',textBox3。文本); 
da.SelectCommand = new SqlCommand(query,cs);


如果你正在做一个类似的陈述,那对我来说意味着你是尝试将多个值从文本框传递到SQL。如果您尝试使用Int32.Parse验证除整数以外的任何内容,则会失败。需要考虑以下几点:



  1. 您应该考虑参数化查询,因为您已将代码保持打开状态,而不是传递这样的参数 SQL注入攻击 [< a href =http://www.codeproject.com/Articles/9378/SQL-Injection-Attacks-and-Some-Tips-on-How-to-Prevtarget =_ blanktitle =New Window> ^ ](你很幸运, Int32.Parse 正在抛出异常,因为它偶然起到了对数据库的保护作用。)
  2. 这样的声明真的是最好的方法吗?考虑一下您最终会得到的执行查询。您可能想要基于表的查询 [ ^ ]。


hii,everyone
How to solve this error(an unhandled exception of type 'System.FormatException'...)

in button search when put characters give me this error .


da.SelectCommand = new SqlCommand("select * from tblcontacts where id like " +Int32.Parse( textBox3.Text), cs);
            dt.Clear();
            da.Fill(dt);

            dataGridView1.DataSource = dt;

解决方案

There is no need to convert to an integer just to convert it back to a string again. Just use:

new SqlCommand("select * from tblcontacts where id like " + textBox3.Text, cs)



But you should learn about parameterized queries and SQL injection attacks. This opens you up to major hacking in your database.


Try this


as Ron said , be aware of SQL_injection[^]

string query = string.Format("select * from tblcontacts where id like '{0}'",textBox3.Text);
       da.SelectCommand = new SqlCommand(query, cs);


If you're doing a like statement, that suggests to me that you are trying to pass multiple values across from your textbox through to your SQL. If you are trying to validate anything other than an integer with Int32.Parse, this will fail. A couple of things need to be considered:

  1. Rather than passing parameters like this, you should consider parameterised queries because you have left the code open to SQL Injection attacks[^] (you're lucky that the Int32.Parse is throwing an exception as that has, by accident, acted as protection for your database).
  2. Is a like statement really the best way to do this? Consider the execution query you will end up with. You might want to put a table based query[^] in there instead.


这篇关于如何解决此错误(类型'System.FormatException'的未处理异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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