日期:2014-05-17  浏览次数:20800 次

C#编程关于DataGridView控件问题
目的:想在查询服务窗体,输入书名或编号时,在DataGridView显示数据库符合条件的数据。当只输入图书编号时,程序可以正常显示符合条件的数据。但只输入书名时,却出现始料未及的问题,调试到第三句代码,捕抓到一个异常。求解!!!求帮忙!!!
代码如下:
string yanzheng = this.textBox1.Text.Trim();
  int id = Int32.Parse(this.textBox2.Text.Trim());
  SqlConnection cnn = new SqlConnection(@"Data Source=DJK-PC;Initial Catalog=图书管理系统;Integrated Security=True");
  cnn.Open();
  SqlCommand cd = new SqlCommand();
  cmd.CommandText = "select * from 图书状态表 where book_name ='" + yanzheng + "'or book_id ='" + id + "' ";
  cmd.Connection = conn;
  SqlDataAdapter ada = new SqlDataAdapter(cmd);
  DataSet ds = new DataSet();
  ada.Fill(ds, "图书状态表");
  dataGridView1.DataSource = ds.Tables["图书状态表"];
  conn.Close();



------解决方案--------------------
int id = Int32.Parse(this.textBox2.Text.Trim()); 

如果你这里图书编号没输为空,parse为报错。。。空值不能转换数值


//改用这个
int id=0;
boolean parse=Int32.TryParse(this.textBox2.Text.Trim(),id);


还有尽量捕获异常 try{} catch(){}
------解决方案--------------------
Int32.Parse(this.textBox2.Text.Trim()),如果是书名,这个不能被转为int,肯定报错
------解决方案--------------------
C# code
string yanzheng = this.textBox1.Text.Trim();

[color=#FF0000]if(textBox2.Text!="")[/color]//加一句判断
int id = Int32.Parse(this.textBox2.Text.Trim());

或者sql
  cmd.CommandText = "select * from 图书状态表 where book_name ='" + textBox1.Text.Trim()+ "'or book_id ='" + textBox2.Text+ "' ";

------解决方案--------------------
不是数字型字符串不能用parse转换为int类型