Click here to Skip to main content
15,897,371 members

How to get and update the value of two dropdownlist s with child-parent relation in gridview that use sqldatasource

elmirag asked:

Open original thread
I have a gridview which shows my products and I can Edit them if I choose Edit in my grid view;
I have two nested DropDownList with child-parent relation in EditItemTemplate in my gridview,the first DropDownList (parent) is related to my products brand and the second DropDownList (child) is related to my products Categories. I mean when user select one Item in in first DropDownList (brands) the Second DropDownList shows the list of categories which is related to selected brand.
relatede code in my gridview:
ASP
 <asp:TemplateField >
 < itemtemplate >
                    <asp:Label ID="brandname" runat="server"Text='<%#Eval("brand_name") %>'> 
 </itemtemplate>
 <edititemtemplate>
                    <asp:DropDownList  ID="brandDrop" runat="server" DataTextField="brand_name" DataValueField="id" DataSourceID="SqlDataSource4" AutoPostBack="true"  >
                    
                   
                    <asp:SqlDataSource ID="SqlDataSource4" runat="server" ConnectionString="<%$ ConnectionStrings:mobile_storeConnectionString2 %>" SelectCommand="select [id],[brand_name] from [brands]" >
</edititemtemplate>
             

<asp:TemplateField>
                <itemtemplate>
                    <asp:Label ID="catname" runat="server" Text='<%# Eval("category_name") %>'>
                </itemtemplate>
                <edititemtemplate>
                   <asp:DropDownList ID="categoryDrop" runat="server" DataTextField="category_name" DataValueField="id" DataSourceID="SqlDataSource3" AutoPostBack="true">
                   
                  
                   <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" DefaultValue="1" 
                        Name="idfrombrands" PropertyName="SelectedValue" Type="Int32"  />
                    </SelectParameters>
                   

 </edititemtemplate>

and this is sqldatasource for my gridview:
ASP
<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
        ConnectionString="<%$ ConnectionStrings:mobile_storeConnectionString3 %>" 
        SelectCommand="SELECT * FROM [AdminProductList]" UpdateCommand="UPDATE AdminProductList SET p_name=@p_name,p_price=@p_price,p_qty=@p_qty,p_Img_S=@path ,idfromCategories=@cat_id,idfrombrands=@brand_id WHERE [id]=@id">
         <updateparameters>
         <asp:Parameter Name="path" DefaultValue="default.gif" />
         <asp:Parameter Name="brand_id " Type="Int32"  DefaultValue="1"/>
         <asp:Parameter Name="cat_id " Type="Int32" DefaultValue="1"/>
         
        </updateparameters>

My problem is I don't know how to get the selected value form dropdownlists, update my sqldatasource1 and data in tables in my database and if the user click on edit but did not select any item from dropdownlists (I mean the user did not edit brands and categories )then I want to store the old data of dropdownlists
I dont know what should I write in GridView1_RowDataBound and GridView1_RowUpdating

and this is my AdminProductList view in database that I use it in sqldatasource1 and my gridview use sqldatasource1:
SQL
SELECT     dbo.brands.id AS brandId, dbo.categories.id AS categoryID, dbo.brands.brand_name, dbo.categories.category_name, dbo.Products.id, dbo.Products.p_name, 
                      dbo.Products.p_price, dbo.Products.p_qty, dbo.Products.p_Img_S, dbo.Products.idfromCategories, dbo.categories.idfrombrands
FROM         dbo.brands INNER JOIN
                      dbo.categories ON dbo.brands.id = dbo.categories.idfrombrands INNER JOIN
                      dbo.Products ON dbo.categories.id = dbo.Products.idfromCategories

This is my code for GridView1_RowUpdating and GridView1_RowDataBound:
C#
  protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        //brandDrop--------------------------------------

        DropDownList list1 = (DropDownList)GridView1.Rows[e.RowIndex].FindControl("brandDrop");
        //Label lbl = (Label)GridView1.Rows[e.RowIndex].FindControl("br");
        int NewIdFromBrand = -1; 
        if (list1.SelectedItem.Value != null)
        {
             NewIdFromBrand = Convert.ToInt32(list1.SelectedItem.Value);
          
            SqlDataSource1.UpdateParameters["brand_id"].DefaultValue = NewIdFromBrand.ToString();

        }
        else
        {
        }
        //categoryDrop----------------------------------------

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

        if (list2.SelectedItem.Value != null)
        {
            SqlDataSource1.UpdateParameters["cat_id"].DefaultValue = list2.SelectedValue;
        }
        else
        {
           

        }

        //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"); //(Label)GridView1.TemplateControl.FindControl("oldImage");
        if (fileUpload != null && fileUpload.HasFile)
        {
            fileUpload.SaveAs(Server.MapPath("~/P_Image") + photoname + fileUpload.FileName);
            //   fileUpload.PostedFile.SaveAs(path + "/" + photoname +filename);
            SqlDataSource1.UpdateParameters["path"].DefaultValue = "~/P_Image" + photoname + fileUpload.FileName;
        }
        else
        {


            SqlDataSource1.UpdateParameters["path"].DefaultValue = lbl3.Text;//oldImage.Text;


        }
        GridView1.EditIndex = -1;
        GridView1.DataBind();
    }

//databound-----------------------------------------------------------

  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[0].ToString();
//dRowView1[0] gives me brandId column in my view
                        
                        DropDownList ddlStatus2 = (DropDownList)e.Row.FindControl("categoryDrop");
                        ddlStatus2.SelectedValue = dRowView1[1].ToString();
//dRowView1[1] gives me categooryID column in my view
                    }
                }
                
            }

        }

I don't know what is wrong with this code, but when I run this page this error is given:
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error:
Line 26:             NewIdFromBrand = Convert.ToInt32(list1.SelectedItem.Value);
Line 27:             Label1.Text = NewIdFromBrand.ToString();
Line 28:             SqlDataSource1.UpdateParameters["brand_id"].DefaultValue = NewIdFromBrand.ToString();
Line 29: 
Line 30:             //SqlDataSource1.UpdateParameters["brand_id"].DefaultValue = list1.SelectedValue;

I used this code in another page but with one DropDowwnList and it works fine.

if anyone help me I will be so thankfull
Tags: ASP.NET

Plain Text
ASM
ASP
ASP.NET
BASIC
BAT
C#
C++
COBOL
CoffeeScript
CSS
Dart
dbase
F#
FORTRAN
HTML
Java
Javascript
Kotlin
Lua
MIDL
MSIL
ObjectiveC
Pascal
PERL
PHP
PowerShell
Python
Razor
Ruby
Scala
Shell
SLN
SQL
Swift
T4
Terminal
TypeScript
VB
VBScript
XML
YAML

Preview



When answering a question please:
  1. Read the question carefully.
  2. Understand that English isn't everyone's first language so be lenient of bad spelling and grammar.
  3. If a question is poorly phrased then either ask for clarification, ignore it, or edit the question and fix the problem. Insults are not welcome.
  4. Don't tell someone to read the manual. Chances are they have and don't get it. Provide an answer or move on to the next question.
Let's work to help developers, not make them feel stupid.
Please note that all posts will be submitted under the http://www.codeproject.com/info/cpol10.aspx.



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900