2013-05-17 39 views
1

在GridView中編輯行時,我需要一個DropDownList,其可用值列表取決於行中的其他列(讓我們說「type」現在的記錄);也就是說,將根據正在編輯的行列出不同的選項。如何在GridView EditItemTemplate中填充DropDownList,具體取決於其他列值

我通過向GridView中添加一個不需要的DataKeyName來獲得它的工作方式,但這導致我在其他地方感到悲傷,無論如何感覺太迂迴,所以我正在尋找更好的方法。下面是我當前如何做:

在.aspx文件:

<asp:GridView ID="gvDct" ... DataKeyNames="dctId,dctType" ... > 
    ... 
    <asp:TemplateField> 
    ... 
    <EditItemTemplate> 
     <asp:DropDownList ID="ddlDctParent" runat="server" 
      DataSourceId="sdsDctParent" 
      DataValueField="dctId" DataTextField="dctFullPath" 
      SelectedValue='<%# Bind("dctParentId") %>' 
      ... > 
     </asp:DropDownList> 
     <asp:SqlDataSource ID="sdsDctParent" runat="server" 
      ConnectionString="<%$ ConnectionStrings:ConnectionString %>" 
      OnSelecting="sdsDctParent_Selecting" 
      SelectCommand="SELECT dctId, dctFullPath FROM lkpDocCatAndType 
          WHERE [email protected]"> 
     <SelectParameters> 
      <asp:Parameter Name="dctType" /> 
     </SelectParameters> 
     </asp:SqlDataSource> 
    </EditItemTemplate> 
    </asp:TemplateField> 
    ... 
</asp:GridView> 

我希望SelectParameter要與控件ID = 「gvDct」 一個ControlParameter和屬性名= 「SelectedDataKey.Values [dctType]」 ,但由於未知的原因,沒有工作(參數值爲空),所以我將此位添加到.vb代碼隱藏文件以填充DropDownList的數據源的行特定參數:

Protected Sub sdsDctParent_Selecting(ByVal sender As Object, _ 
      ByVal e As System.Web.UI.WebControls.SqlDataSourceSelectingEventArgs) 
    e.Command.Parameters(0).Value = gvDct.DataKeys(gvDct.EditIndex).Item(1) 
End Sub 

所以,當我開始在GridView中編輯一行時,DropDownL ist被綁定,這會導致SqlDataSource SelectCommand執行,這會觸發OnSelecting代碼,我將從正在編輯的行(EditIndex)提供參數值,以便在DropDownList中獲取適當的值。

有沒有「更好」的方法?對我來說最重要的方面是避免添加DataKeyName,因爲這會導致我用於從GridView中刪除一行的存儲過程出現太多參數問題。

+0

是不是上面的代碼中容易出現SQL注入? – bonCodigo

回答

0

您應該使用的GridView RowDataBound在那裏你可以在以後你可以填充你的Dropdownlist還添加了label/hidden場要填充下拉列表
Sry基因在C#編寫代碼,其值取VALUEID。

你可以嘗試這樣的事情

protected void gvDct_RowDataBound(object sender, GridViewRowEventArgs e) 
{ 
if (e.Row.RowType == DataControlRowType.DataRow) 
    { 
    if ((e.Row.RowState & DataControlRowState.Edit) > 0) 
    { 
     Label lblValue = (Label)e.Row.FindControl("YourLableID") 
     DropDownList ddList= (DropDownList)e.Row.FindControl("ddlDctParent"); 
     //bind dropdownlist 
     DataTable dt = con.GetData("Select Query where YourColumn='"+lblValue.text+"'"); 
     ddList.DataSource = dt; 
     ddList.DataTextField = "dctFullPath"; 
     ddList.DataValueField = "dctId"; 
     ddList.DataBind(); 

     DataRowView dr = e.Row.DataItem as DataRowView; 
     ddList.SelectedValue = dr["dctId"].ToString(); 
    } 
    } 
} 
+1

GridViewEditEventArgs不包含Row屬性 改爲使用GridViewRowEventArgs – concept

+0

RowCommand事件是否會比RowDataBound更好? – bonCodigo

相關問題