2016-02-09 61 views
0
protected void dgMenuSubItems_ItemCommand(object source, DataGridCommandEventArgs e) 
{ 
    try 
    { 
     if (!(e.CommandName == "AddANewRow")) 
      return; 

     string str1 = this.dgMenuItems.DataKeys[this.dgMenuItems.SelectedIndex].ToString(); 

     TextBox textBox1 = e.Item.FindControl("txtSubItemNameF") as TextBox; 
     TextBox textBox2 = e.Item.FindControl("txtSubItemPriceF") as TextBox; 
     TextBox textBox3 = e.Item.FindControl("txtSubItemSortOrderF") as TextBox; 

     if (textBox1 != null && textBox2 != null) 
     { 
      int num = Convert.ToInt32(clsADO.getSingleRecord("Select Max(SubItemId) from tbl_MenuSubItems")); 
      string text1 = textBox1.Text; 
      string text2 = textBox2.Text; 
      string str2 = text1.Replace("''", "''"); 
      string str3; 

      try 
      { 
       str3 = Convert.ToInt32(textBox3.Text).ToString(); 
      } 
      catch 
      { 
       str3 = "0"; 
      } 

      clsADO.executeNonQuery("Insert into tbl_MenuSubItems values ('" + (object) (num + 1) + '",'" + str2 + "','" + text2 + "','" + str1 + "','" + str3 + "')"); 
     } 
     else 
      this.lblError.Text = "Error finding the SubItem"; 

     this.Rebuild_Sub_Display(); 
    } 
    catch (Exception ex) 
    { 
     this.lblError.Text = ex.Message; 
    } 
} 

在這裏,我將值插入到數據庫中,但我發現了錯誤:C#,ado.net,Asp.net

Unclosed quotation mark after the character string ',0)'. Incorrect syntax near ',0)'

我覺得我缺少一個引號,但我不」不知道我在哪裏丟失它

+1

您應該使用的參數。這樣,如果用戶將文本放在了文本中,那麼這將失敗,而SQL注入則會失敗。 –

+2

請在執行sql查詢時使用SqlCommand而不是純文本。也像@NikhilAgrawal說,你應該正確地添加參數。請參閱[此鏈接](https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.parameters(v = vs.110).aspx)以獲取更多信息 –

+0

不應該將此'字符串str2 = text1.Replace(「''」,「''」);'是'字符串str2 = text1.Replace(「'」,「''」);' –

回答

0

你應該使用sqlcommand和sqlparameters來做到這一切。反正 您插入查詢必須是這樣的,你做不正確的字符串

Insert into tbl_MenuSubItems values ('" + (object) (num + 1) + "','" + str2 + "','" + text2 + "','" + str1 + "','" + str3 + "') 

您的非查詢行必須是

clsADO.executeNonQuery("Insert into tbl_MenuSubItems values ('" + (object) (num + 1) + "','" + str2 + "','" + text2 + "','" + str1 + "','" + str3 + "')");