2014-04-05 284 views
0

这里是我的C#代码C#asp.net字符串比较

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e) 
{ 
    TextBox25.Text = DateTime.Now.ToString("MM/yy"); 

    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["preconn"].ToString()); 

    con.Open(); 

    SqlCommand com = new SqlCommand("select * from employe Where user_id = '" + DropDownList1.SelectedItem.Value + "'", con); 

    SqlDataReader reader = com.ExecuteReader(); 

    if (reader.Read()) 
    { 
     TextBox1.Text = reader["Id"].ToString(); 
    } 
    con.Close(); 
} 

protected void Button1_Click(object sender, EventArgs e) 
    { 

     string user1 = Convert.ToString(TextBox25.Text); 

     SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["preconn"].ToString()); 

     con.Open(); 

     SqlCommand com2 = new SqlCommand("select * from salary where id='" + DropDownList1.SelectedItem.Text + "'", con); 

     SqlDataReader reader1 = com2.ExecuteReader(); 

     if (reader1.Read()) 
     { 
      string user; 
      user = Convert.ToString(reader1["month"]); 

      //if (TextBox25.Text == user) 
      if (user1.CompareTo(user)==0) 
      { 
       Label9.Visible = true; 
       Label9.Text = "Salary already updated please check again"; 
      } 
     }// user check end 

     else 
     { 

      SqlCommand com1 = new SqlCommand("insert into salary values(@id,@work_days,@month)",con); 

      SqlParameter obj1 = new SqlParameter("@id", DbType.StringFixedLength); 
      obj1.Value = DropDownList1.SelectedItem.Value; 
      com1.Parameters.Add(obj1); 

      SqlParameter obj2 = new SqlParameter("@work_days", DbType.StringFixedLength); 
      obj2.Value = TextBox10.Text; 
      com1.Parameters.Add(obj2); 

      SqlParameter obj15 = new SqlParameter("@month", DbType.StringFixedLength); 
      obj15.Value = TextBox25.Text; 
      com1.Parameters.Add(obj15); 

      com1.ExecuteNonQuery(); 

      con.Close(); 


     } 

    } 

当我点击Button1的,数据不插入任何错误消息显示。 我认为这个问题是在我的病情,如果(user1.CompareTo(用户)== 0)

我使用SQL Server 2008中的Visual Studio 2010

+5

您是否调试过此代码以遵循它正在做的事情?这段代码中有很多怪异的东西,你应该尝试清理它们。例如,你在已经是字符串的东西上使用'Convert.ToString'。然后,您将名为“month”的列的内容存储到名为user的变量中。你已经让这段代码非常容易混淆,难道你自己也会困惑吗? –

+0

请确保始终如一地使用参数化查询。它不仅可以避免许多您尚未关注的[SQL注入](http://en.wikipedia.org/wiki/SQL_injection),但可能会帮助您将随机文本传递到SQL。 –

回答

0

我认为你必须做这样的事情

user = Convert.ToString(reader1['rowIndex']["month"]); 

其中RowIndex是一个整数