private void button1_Click(object sender, System.EventArgs e)
  {
     if(this.textBox1.Text == "")
{
   MessageBox.Show("请输入欲删除的用户名!");
         }
     else 
{
   SqlConnection myConnection = new SqlConnection(Form1.myConnectionString);
   SqlCommand myCommand = new SqlCommand();
   myCommand.Connection = myConnection;
   myCommand.CommandText = "delete from adiminstator where ID ='" + this.textBox1.Text + "' and Type != '0'";
      try
{
myConnection.Open();
myCommand.ExecuteNonQuery();
myConnection.Close();
MessageBox.Show("删除用户成功!");
}
      catch(Exception i)
{
         MessageBox.Show("用户不存在,请更改用户名!");
}
}
按理说,如果我删除一个不存在的用户,那么应该说“用户不存在,请更改用户名!”,可却是不论怎么都是返回"删除用户成功!"。到底怎么的?谢谢!!

解决方案 »

  1.   

    下面是我的另一段几乎一样的代码,却是正常。也就是sql 语句不一样而已。救急啊!
    if(this.textBox1.Text == "" || this.textBox2.Text == "" || this.comboBox1.Text == "")
    {
    MessageBox.Show("请保证参数完整!");
    }
    else 
    {
    SqlConnection myConnection = new SqlConnection(Form1.myConnectionString);
    SqlCommand myCommand = new SqlCommand();
    myCommand.Connection = myConnection;
    myCommand.CommandText = "insert into adiminstator (ID,Password,Type)" + "values('" + this.textBox1.Text + "','" + this.textBox2.Text +"','" + this.comboBox1.Text + "')";
    try
    {
    myConnection.Open();
    myCommand.ExecuteNonQuery();
    myConnection.Close();
    MessageBox.Show("添加用户成功!");
    }
    catch(Exception i)
    {
    MessageBox.Show("用户已存在,请更改用户名!");
    }
    }

    }
      

  2.   

    通过try合catch来判断试没有用的
    因为你这个操作没有发生异常
    (当没有这个id的时候只是不删除任何记录但是不会发生异常)
    你可以通过得到更新的记录数目来判断
    int i=myCommand.ExecuteNonQuery();
    if(i==0)
    MessageBox.Show("用户不存在,请更改用户名!");
    else
    MessageBox.Show("删除用户成功!");
      

  3.   

    谢谢你,不过还是有些小问题,根据你的代码,有一个问题:当用户存在的时候,如果我删除,那么还是返回信息("用户不存在,请更改用户名!")同时数据库中的用户也被删除了。似乎int i=myCommand.ExecuteNonQuery();
    if(i==0)
    无法判断呢?
      

  4.   

    使用try(System.Data.SqlCLinet.SqlException ee)
    catch(System.Data.SqlCLinet.SqlException ee)试试