Search code examples
asp.netgridviewcascadingdropdown

Dropdownlists with parent-child relation in EditItemTemplate Gridview not working


I have a page with gridview in it.
My gridview shows the products Information and Admin can Edit gridviews columns.
Two of my columns show the brand name and category name for each product;
I use lables in ItemTemplate tag in my grid view to show these two columns value and I use two dropdownlists(branddrop,categorydrop)
in my EditItemTemplate tag for editing these two columns value,when admin select an item in branddrop the categorydrop should show categories name which are related to selected brand name in branddrop.

Brands name in my brand table in database are:

Samsung, Nokia,Sony Ericsson,Apple,LG,HTC....

and my categories name in category table are :

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...


When I click the Edit button, first item in the branddrop is Equal to brandlable.

Text in ItemTemplate and it works fine my problem is the first item in category drop is not Equal to categorylable.

text in ItemTemplate and the category drop does not show the related categories name to brandname.
for every product it shows iphone and ipad so I have to select another items in branddrop and then select again the related brandname which is related to that product then the categorydrop can show the list of related categories name.

I tried to use brandDrop_SelectedIndexChanged and GridView1_RowEditing but it is not work.

I dont know how to solve it.

this is my first code:

<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>

this is my code behind for GridView1_RowDataBound and 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;

                }
            }

        }

    }
}

Solution

  • Thank you so much Abide Masaraure.you helped me a lot. I deleted grideview_rowediting and braddrop_selectedIndexChange event And just added two lines to my GridView1_RowDataBound event.

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

    now my event is like this:

      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();
                    }
                }
    
            }
    
        }
    }