private void button2_Click(object sender, EventArgs e)
        {  
            DataSet ds=new DataSet();
            if (dataGridView1.CurrentCell != null)
            {
                //string str = this.dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex].Cells["specialtyid"].Value.ToString();
                string str = dataGridView1.CurrentRow.Cells[0].Value.ToString(); 
               // string str=this.dataGridView1.SelectedRows[0].Cells[1].Value.ToString();
                string sql = "select specialtyname from specialtyinfo where specialtyid='" + str + "'and specialtyid not in (select distinct specialtyinfo.specialtyid from classinfo inner join specialtyinfo on classinfo.specialtyname=specialtyinfo.specialtyname)";
                OleDbCommand cmd = new OleDbCommand(sql, connection1);
                OleDbDataReader dr;
                dr = cmd.ExecuteReader();
                cmd.CommandText = sql;
                cmd.ExecuteNonQuery();
                if (!dr.Read())
                {
                    MessageBox.Show("删除专业'" + str+ "'失败,请先删除与专业相关的班级", "提示");
                    dr.Close();
                }
               else
                {
                    dr.Close();
                    sql="delete * from specialtyinfo where specialtyname not in (select distinct specialtyname from classinfo) and specialtyid="+str;
                    cmd.CommandText = sql;
                    cmd.ExecuteNonQuery();
                   MessageBox.Show("删除专业成功", "提示");
               }
            }
            
        }
这是个删除按钮,请问这里哪里错了 现在运行时dr = cmd.ExecuteReader();标准表达式中数据类型不对,是不是str语句错了啊?怎么改呢?

解决方案 »

  1.   

    1、执行sql之前看看值是啥
    dataGridView1.CurrentRow.Cells[0].Value.ToString(); 
    如果不是数字,自然错
    2、也可以调试时把如下sql的值用断点断下来看看
    sql=string.Format("delete * from specialtyinfo where specialtyname not in (select distinct specialtyname from classinfo) and specialtyid='{0}'",str);
    3、不要用这种方式,dataGridView1.CurrentRow.Cells[0].Value.ToString(); 易出错!
    应该用FindByControl方式 
    这里
    http://www.cnblogs.com/downmoon/archive/2008/12/04/1347581.html
    http://www.cnblogs.com/downmoon/archive/2007/12/30/1021151.htmlhttp://blog.csdn.net/downmoon/archive/2007/12/14/1935654.aspx
    http://blog.csdn.net/downmoon/archive/2008/12/05/3444429.aspx
      

  2.   

    where specialtyid='" + str + "'and specialtyid 注意连接SQL语句的时候 虽然加上了变量STR  但是  AND前面的空格还是要加上的。。检查一下 是否是连接语句中间的空格没加上。。