EditItemTemplate Gridview中具有父子关系的下拉列表无法正常工作

时间:2013-01-03 11:53:00

标签: asp.net gridview cascadingdropdown

我的页面中包含gridview
我的gridview会显示产品信息和管理员Edit gridviews columns。 我的两个columns显示每个产品的brand namecategory name;
我在网格视图中的ItemTemplate标签中使用标签来显示这两列值,我使用两个dropdownlists(branddrop,categorydrop)
在我的EditItemTemplate标签中编辑这两列值,当管理员选择branddrop中的项目时,categorydrop应显示与branddrop中所选品牌名称相关的类别名称。

数据库中我的品牌表中的品牌名称是:

  

三星,诺基亚,索尼爱立信,Apple,LG,HTC ....

和类别表中的类别名称是:

  

Galaxy Nexus,Galaxy Tab 2 7. 0,Galaxy S3,Asha,Lumia,iPhone,iPad,Xperia Arc,Xperia Neo,Xperia X8,Cookie 3g,Cookie lite,Km555e,Optimus l9,Optimus elite,Optimus g, wt18i,w8,500,n8 ...


当我点击Edit button时,branddrop中的第一项与品牌相等。

在ItemTemplate中的文本,它工作正常我的问题是类别drop中的第一项不等于可分类。
在ItemTemplate中的文本和类别drop不显示品牌名称的相关类别名称。
对于每个产品,它显示iphone和ipad,所以我必须在branddrop中选择另一个项目,然后再次选择与该产品相关的相关品牌名称,然后categorydrop可以显示相关类别名称列表。

我尝试使用brandDrop_SelectedIndexChangedGridView1_RowEditing,但这不起作用。

我不知道如何解决。

这是我的第一个代码:

<asp:TemplateField HeaderText="brand name">
            <ItemTemplate>
                <asp:Label ID="brandname" runat="server" Text='<%#Eval("brand_name") %>'></asp:Label>
                <asp:Label ID="idfrombrand" runat="server" Text='<%#Eval("idfrombrands") %>' Visible="false"></asp:Label>
            </ItemTemplate>
            <EditItemTemplate>
                <asp:Label ID="br" runat="server" Text='<%# Eval("idfrombrands") %>' Visible="false"></asp:Label><%--OnSelectedIndexChanged="brandDrop_SelectedIndexChanged" --%> 

                <asp:DropDownList  ID="brandDrop" runat="server" DataTextField="brand_name" DataValueField="id" DataSourceID="SqlDataSource4" AutoPostBack="true"  OnSelectedIndexChanged="brandDrop_SelectedIndexChanged" >
                </asp:DropDownList>
                <asp:SqlDataSource ID="SqlDataSource4" runat="server" ConnectionString="<%$ ConnectionStrings:mobile_storeConnectionString2 %>" SelectCommand="select [id],[brand_name] from [brands]" ></asp:SqlDataSource>
            </EditItemTemplate>
         </asp:TemplateField>

        <asp:TemplateField HeaderText="category name">
            <ItemTemplate>
                <asp:Label ID="catname" runat="server" Text='<%# Eval("category_name") %>'></asp:Label>
            </ItemTemplate>
           <EditItemTemplate>
               <asp:Label ID="OldCatName" runat="server" Text='<%# Eval("idfromCategories") %>' Visible="false"></asp:Label>
               <asp:DropDownList ID="categoryDrop" runat="server"  AutoPostBack="true" DataTextField="category_name" DataValueField="id" DataSourceID="SqlDataSource3">   <%-- --%>
               </asp:DropDownList>
               <asp:Label ID="cat" runat="server" Text='<%# Eval("idfromCategories") %>' Visible="false" ></asp:Label>
              <asp:SqlDataSource ID="SqlDataSource3" runat="server"   ConnectionString="<%$ ConnectionStrings:mobile_storeConnectionString2 %>" SelectCommand="select [category_name],[id],[idfrombrands] from [categories] where idfrombrands=@idfrombrands " >
                <SelectParameters>
                  <asp:ControlParameter ControlID="brandDrop" 
                    Name="idfrombrands" PropertyName="SelectedValue" Type="Int32"  />
                </SelectParameters>
               </asp:SqlDataSource>

           </EditItemTemplate>
        </asp:TemplateField>
  

这是GridView1_RowDataBound和GridView1_RowUpdating背后的代码:

 protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
     int brand=0;
    int category=0;
    //Drop Brand--------------------------------------

    DropDownList list1 = (DropDownList)GridView1.Rows[e.RowIndex].FindControl("brandDrop");
    Label lbl = (Label)GridView1.Rows[e.RowIndex].FindControl("br");

    if (list1.SelectedItem.Value != null)
    {
       brand  = Convert.ToInt32(list1.SelectedItem.Value);//NewIdFromBrand

    }
    else
    {
        brand = Convert.ToInt32(lbl.Text);

    }
    //Drop Category----------------------------------------

   DropDownList list2 = (DropDownList)GridView1.Rows[e.RowIndex].FindControl("categoryDrop");
   Label lbl2 = (Label)GridView1.Rows[e.RowIndex].FindControl("OldCatName");

    //int NewIdFromBrand2 = -1;
    if (list2.SelectedItem.Value != null)
    {
       category  = Convert.ToInt32(list2.SelectedItem.Value);//NewIdFromBrand2

    }
    else
    {

        category = Convert.ToInt32(lbl2.Text);
    }

    //Photo-------------------------------------------

    string photoname = System.Guid.NewGuid().ToString();

    GridViewRow row = GridView1.Rows[e.RowIndex];
    FileUpload fileUpload = row.FindControl("FileUploadimg") as FileUpload;
    Label lbl3 = (Label)GridView1.Rows[e.RowIndex].FindControl("oldImage"); 
    if (fileUpload != null && fileUpload.HasFile)
    {
        fileUpload.SaveAs(Server.MapPath("~/P_Image") + photoname + fileUpload.FileName);

        SqlDataSource1.UpdateParameters["path"].DefaultValue = "~/P_Image" + photoname + fileUpload.FileName;
    }
    else
    {
     SqlDataSource1.UpdateParameters["path"].DefaultValue = lbl3.Text;//oldImage.Text;
    }
    int prid = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value);
    SqlConnection cn = new SqlConnection();
    cn.ConnectionString = "server = . ; database = mobile_store ; Trusted_Connection=true";
    DataTable tb = new DataTable();
    SqlCommand cmd = new SqlCommand();
    cmd.Connection = cn;
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.CommandText = "UpdateProduct";
    cmd.Parameters.AddWithValue("@brandid", brand );
    cmd.Parameters.AddWithValue("@catid", category );
    cmd.Parameters.AddWithValue("@pid", prid);
    try
    {
        cn.Open();
        cmd.ExecuteNonQuery();
        SqlDataSource1.DataBind();

    }
    catch (Exception ex2)
    {


    }
    finally { cn.Close(); }
    //GridView1.EditIndex = -1;
    //GridView1.DataBind();

}

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        //check if is in edit mode
        if ((e.Row.RowState & DataControlRowState.Edit) > 0)
        {
            DataRowView dRowView1 = (DataRowView)e.Row.DataItem;
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                if ((e.Row.RowState & DataControlRowState.Edit) > 0)
                {
                    DropDownList ddlStatus = (DropDownList)e.Row.FindControl("brandDrop");
                    ddlStatus.SelectedValue = dRowView1["brandId"].ToString();
                    DropDownList ddlStatus2 = (DropDownList)e.Row.FindControl("categoryDrop");
                    ddlStatus2.SelectedValue = dRowView1["categoryID"].ToString();
                    //Label1.Text = ddlStatus.SelectedValue;

                }
            }

        }

    }
}

4 个答案:

答案 0 :(得分:1)

非常感谢Abide Masaraure.you帮了我很多忙。 我删除了grideview_rowediting和braddrop_selectedIndexChange事件并且只在我的GridView1_RowDataBound事件中添加了两行。

 SqlDataSource sq = (SqlDataSource)e.Row.FindControl("SqlDataSource3");
 sq.SelectParameters["idfrombrands"].DefaultValue = dRowView1["brandId"].ToString();

现在我的活动是这样的:

  protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        //check if is in edit mode
        if ((e.Row.RowState & DataControlRowState.Edit) > 0)
        {
            DataRowView dRowView1 = (DataRowView)e.Row.DataItem;
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                if ((e.Row.RowState & DataControlRowState.Edit) > 0)
                {
                    DropDownList ddlStatus = (DropDownList)e.Row.FindControl("brandDrop");
                    ddlStatus.SelectedValue = dRowView1["brandId"].ToString();
                    DropDownList ddlStatus2 = (DropDownList)e.Row.FindControl("categoryDrop");
                    ddlStatus2.SelectedValue = dRowView1["categoryID"].ToString();

                    SqlDataSource sq = (SqlDataSource)e.Row.FindControl("SqlDataSource3");
                    sq.SelectParameters["idfrombrands"].DefaultValue = dRowView1["brandId"].ToString();
                }
            }

        }

    }
}

答案 1 :(得分:0)

我需要查看您在所选索引更改事件中使用的代码。

以下级联下拉技术将消除您在尝试连接父级及其子级时所遭受的所有痛苦......我在所有项目中使用Ajax控件工具包中的这个奇妙功能。您可以使用任何数据只要它返回一个数组,你想要的检索方法。我在这个例子中使用linq进行数据检索。 假设我有名为Brand和Model和类的表:品牌和模型以及集合:品牌和模型

在'YourWebServicePath.asmx'(网络服务文件)

 <WebMethod()> _
    Public Function GetBrands(knownCategoryValues As String, category As String) As  CascadingDropDownNameValue()

        Dim result = From b As Bands In Brand.Brands Select New CascadingDropDownNameValue(b.BrandDesc, b.BrandID.ToString())
        Return result.ToArray()

    End Function


<WebMethod()> _
Public Function GetModels(knownCategoryValues As String, category As String) As CascadingDropDownNameValue()
    Dim brandID As Guid
    Dim brandValues As StringDictionary = AjaxControlToolkit.CascadingDropDown._
   ParseKnownCategoryValuesString(knownCategoryValues)
     brandID = New Guid(brandValues("Brand"))
    Dim result = From m As Models In Model.GetModels() Where m.brandID = brandID       Select New CascadingDropDownNameValue(m.ModelDesc, 
 _ m.ModelID.ToString())
    Return result.ToArray()
   End Function

<强>标记

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>

    <EditItemTemplate>

                <asp:DropDownList  ID="dropBrand" runat="server" AutoPostBack="true" >
                </asp:DropDownList>


                    <cc1:CascadingDropDown ID="BrandCascadingDropDown"
                                           runat="server"
                                           Category="Brand"
                                           TargetControlID="dropBrand"
                                           PromptText="-Select Brand-"
                                           LoadingText="Loading Brands.."
                                           ServicePath="YourWebServicePath.asmx"

                                           ServiceMethod="GetBrands">
                   </cc1:CascadingDropDown>

</EditItemTemplate>

<EditItemTemplate>
                <asp:DropDownList  ID="dropModel" runat="server" AutoPostBack="true" >
                </asp:DropDownList>


           <cc1:CascadingDropDown ID="ModelCascadingDropDown"
                                           runat="server"
                                           Category="Model"
                                           TargetControlID="dropModel"
                                           ParentControlID="dropBrand"
                                           PromptText="-Select Model-"
                                           LoadingText="Loading Models.."

                                           ServicePath="YourWebServicePath.asmx"
                                           ServiceMethod="GetModels" >
                    </cc1:CascadingDropDown>

这就是你所需要的。不需要为事件接线。瞧!让工具包发挥魔力。

答案 2 :(得分:0)

Eureka !!!。你欠我一杯咖啡。我复制了你的问题,并在两小时后意识到你需要实际挂钩你的索引选择更改的事件。诀窍是使用命名容器属性来定位你的下降,他们认为非常隐蔽,但发送者参数使我们能够在dropband下拉列表时公开它们。并且presto一切都像魅力一样。

在您选择的已更改活动中使用此代码snipet。

protected void dropBand_SelectedIndexChanged(object sender, System.EventArgs e)
{

DropDownList dropBand = (DropDownList)sender;

SqlDataSource dsc = (SqlDataSource)dropBand.NamingContainer.FindControl("SqlDataSource3");
DropDownList categoryDrop = (DropDownList)dropBand.NamingContainer.FindControl("categoryDrop");
dsc.SelectParameters("BrandID").DefaultValue = dropBand.SelectedValue;
categoryDrop.DataBind();
}

如果你碰巧继续发行,我可以给你发送一个演示文件的zip文件。快乐的编码!!! Debug

答案 3 :(得分:0)

要使用上面的代码,我连续编辑了你必须修改它的事件。那么这些对象不会为空。

 protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
    GridView testgrid = (GridView)(sender);
    testgrid.EditIndex = e.NewEditIndex;
    testgrid.DataBind();
    DropDownList dropBand = (DropDownList)testgrid.Rows[e.NewEditIndex].FindControl("ddlProducts");

    //
}

在您的页面循环中肯定会发生一些事情并且一直在咬你。我建议压缩你的数据库的mdf和违规的aspx页面,让我从这里解决它,如果你不能让它工作。永远不要给起来。

enter image description here

相关问题