2013-05-17 45 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

相关问题