2015-07-03 89 views
0

Me中理解@變量時出現問題。我無法理解位於查詢中的@variables。再次在更新查詢

例如:

UPDATE tbSystems SET Systems = @Systems WHERE id = @id 

我試圖從具有AutoGenerateEditButton屬性爲True gridview的升級日期。這裏是aspx文件:

   <asp:GridView ID="gv1" 
        runat="server" 
        CellPadding="2" 
        DataKeyNames="id" 
        AutoGenerateDeleteButton="True" 
        AutoGenerateEditButton="True" 
        OnRowDeleting="gv1_RowDeleting" 
        OnRowDeleted="gv1_RowDeleted" 
        OnRowUpdating="gv1_RowUpdating"> 
       </asp:GridView> 

,這是該OnRowUpdating函數調用的函數:

protected void gv1_RowUpdating(object sender, GridViewUpdateEventArgs e) 
     { 
      switch (strType) 
      { 
       case "servers": 
        Response.Write("1"); 
        break; 
       case "systems": 
        DS.UpdateCommand = "UPDATE tbSystems SET Systems = @Systems WHERE id = @id"; 
        break; 
       case "itOwners": 
        Response.Write("3"); 
        break; 
       case "systemOwners": 
        Response.Write("4"); 
        break; 
       default: 
        break; 
      } 
      gv1.EditIndex = -1; 
      gv1.DataSourceID = DS.ID; 
      gv1.DataBind(); 
     } 

我一直在測試一兩件事情沒有任何成功。

試過:

  • 系統添加到的DataKeyNames。這可以防止在Gridview中創建文本框。
  • 做了一個系統參數添加到SqlDataSource。這給了我一個錯誤,告訴我係統變量已經存在。
  • 獲取Gridview編輯文本框中的信息沒有任何成功。遠離獲得原始價值不是新的價值。

下面是我的一些問題:

  1. 如果只使用了的DataKeyNames識別主鍵?
  2. 如何獲取由gridview的編輯選項創建的文本框中輸入的信息?
  3. 如何獲取或設置@variables中的信息?

謝謝,

+4

它們是參數,請參見:[SqlParameter](https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlparameter(v = vs.110).aspx) – Habib

+3

使用參數作爲一種預防SQL注入的佔位符。 –

回答

1

1.Should只使用了的DataKeyNames識別主鍵?

2.How做我得到由GridView控件的編輯選項創建的文本框中輸入的信息?

你必須做一個回發,然後你可以從gridview對象中檢索它們。

3.如何獲取或設置@variables中的信息?

這些都爲參數發送到數據庫變量,工作這樣的事情

string sql = "UPDATE tbSystems SET Systems = @Systems WHERE id = @id"; 
SqlConnection connection = new SqlConnection("your connection string"); 
SqlCommand command = new SqlCommand(sql, connection); 

SqlParameter param = new SqlParameter(); 
      param.ParameterName = "@Systems"; 
      param.Value   = systems; 

command.Parameters.Add(param); 

SqlParameter paramId = new SqlParameter(); 
      paramId.ParameterName = "@id"; 
      paramId.Value   = Id; 

command.Parameters.Add(paramId); 

編輯,顯示參數對象的創建。

+1

'.AddWithValue()'已知是有問題的。我建議使用'Parameters.Add()。價值'替代。 –

+0

是的,你是對的 – Thorarins

+0

從那裏不應該我只是打開連接,執行SqlCommand並關閉連接?我已將靜態值進行測試,並且不會更改我的數據庫中的值。 – Rimo72