• How to get Dropdown selected value inside GridView using Javascript

    Posted on February 16, 2013 by in ASP.NET, C#, Dotnet

    In this article, I am going to explain how to read dropdown control inside GridView using Javascript. Even though this is a JQUERY world, we still use javascript in most of the web applications.  So we fetch some products from database, and will bind them to the gridview. When user clicks on print button, we get checked rows from gridview and them to a table

    If you are new to using GridView, you could refer to following articles.
    Using GridView in ASP.NET & C# — PART 1
    Using GridView in ASP.NET & C# — PART 2
    How to Insert, Update & Delete rows in ASP.NET GridView Control

    Since the focus of this article is about fetching drop down functions using javascript, I will get to that right away and move The actual page design, bindind data explanation to the end. Added a simple button to the page. When the user clicks on the button, we invoke fnPrintRows where we iterate through gridview rows and add them as rows to a HTML table tblProducts.

    <input type="button" onclick="javascript:fnPrintRows()" value="Print" />
    <table id="tblProducts" runat="server" class="tableClass">
                <tr>
                    <th>Product ID</th>				
    			    <th>Product Number</th>
    			    <th>Product Name</th>
    			    <th>Price</th>
    			    <th>SubCategory</th>
                </tr>
    </table>
    

    Created following class variables (javascript), which would be later used in other javascript functions.

    var gridViewCtlId = '<%=gvProducts.ClientID%>'; // gridview client ID
    var ctlTableProductsID = '<%=tblProducts.ClientID%>'; //tblproducts client ID
    var ctlGridViewProducts = null; //variable to store gridview control
    var ctlTableProducts = null; //variable to store products table control
    

    In the getControls javascript function, we get reference to gridview & products table by invoking document.GetElementByID based on their clientID’s.

    function getControls()
    {
        if (null == ctlGridViewProducts)
        {
            ctlGridViewProducts = document.getElementById(gridViewCtlId);
        }
        if (null == ctlTableProducts) {
            ctlTableProducts = document.getElementById(ctlTableProductsID);
        }
    }
    

    In the fnPrintRows javscript function, we iterate through all gridview rows, as we iterate through rows of a table. Each cell in the row represents each product attribute.  We fetch product attributes from these cells and add them to the tblProducts by calling fnAddRow function.  As you would notice below, the logic to fetch checkbox and dropdown selected value is little bit different. We have to look at the controls in the child nodes to get actual values.  Befor we add the product row to the table, we check if that checkbox is actually checked.

    function fnPrintRows() {           
               getControls();
               var rowCount = ctlGridViewProducts.rows.length;
               //clear all current rows
               fnDeleteRows();
               var productID, productName, productNumber, productPrice, subCategoryName, selectedIndex, isChecked;
               var currRow;
               for (i = 1; i < rowCount - 1; i++) {
                   currRow = ctlGridViewProducts.rows[i];
                   productID = currRow.cells[1].innerText;
                   productName = currRow.cells[2].innerText;
                   productNumber = currRow.cells[3].innerText;
                   productPrice = currRow.cells[4].innerText;
                   selectedIndex = currRow.cells[5].childNodes[1].selectedIndex;
                   subCategoryName = currRow.cells[5].childNodes[1].options[selectedIndex].text;
                   isChecked = currRow.cells[0].childNodes[1].checked;
                   if (isChecked == true) {
                       fnAddRow(productID, productName, productNumber, productPrice, subCategoryName);
                   }
               }
           }
    function fnDeleteRows()
           {
            for(var i = document.getElementById("tblProducts").rows.length; i > 1;i--)
            {
                document.getElementById("tblProducts").deleteRow(i -1);
            }
           }   
    

    In fnAddRow function, we invoke insertRow function to add a new row to the table. Next we create a table cell for each product attribute and add them to the row.

    function fnAddRow(productID, productName, productNumber, productPrice, subCategoryName) {
       var tableRowCount = ctlTableProducts.rows.length;
       var row = ctlTableProducts.insertRow(tableRowCount);
       var cell, element;
    
       cell = row.insertCell(0);
       cell.innerHTML = productID;
    
       cell = row.insertCell(1);
       cell.innerHTML = productName;
    
       cell = row.insertCell(2);
       cell.innerHTML = productNumber;
    
       cell = row.insertCell(3);
       cell.align = "right";
       cell.innerHTML = productPrice;
    
       cell = row.insertCell(4);
       cell.innerHTML = subCategoryName;
    }
    

    Run the application and you would see the following page with top 10 products from the database.
    get dropdown selected value inside gridview using javascript 1 1

    Click on “Print” button and you would notice that checked products from the gridview are added to tblProducts table
    get dropdown selected value inside gridview using javascript 2

    Database Connection
    I am using Adventure Works provided by Microsoft as datasource. Open web.config and add following entry to connection strings element.

    <add name="Sql" connectionString="Data Source=(local);
         Initial Catalog= TEST;User=testuser;Password=testuser;" providerName="System.Data.SqlClient"/>
    

    DataSource
    I am using SQLDataSource to load products from/to database. The ConnectionString property of the SqlDataSource control specifies how to connect to the database. This property can be a hard-coded connection string or can point to a connection string in a Web.config file as shown in the code given above. The SelectCommand property specifies the SQL statement to execute to retrieve the data.

    <asp:SqlDataSource ID="sqlDSProducts" runat="server" 
        ConnectionString="<%$ ConnectionStrings:Sql %>"
       SelectCommand="SELECT top 10 P.ProductID, P.Name, P.ProductNumber, P.ListPrice, P.ProductSubcategoryID,
    		PS.Name AS SubCategoryName FROM Production.Product P
            INNER JOIN Production.ProductSubcategory PS ON P.ProductSubcategoryID = PS.ProductSubcategoryID">
        </asp:SqlDataSource>
    

    Page Design
    Create a new ASP.NET web page and add a gridview to the page.  ProductID, Product Number, Product Name & Price are rendered in Bound Columns/ Template Columns. A checkbox control is added to the grid rendered in a TemplateField as shown below at the row level.   We load sub categories in a drop down list and user can select an item from it. The OnRowDataBound property of the gridview is set to our custom handler gvProducts_RowDataBound. In order to bind the datasource to gridview, set the DataSourceID property to sqldatasource control ID (sqlDSProducts).

    <asp:GridView ID="gvProducts" AutoGenerateColumns="False"  CssClass="mGrid"     
    runat="server" DataSourceID="sqlDSProducts" OnRowDataBound="gvProducts_RowDataBound">         
    <Columns>
        <asp:TemplateField>         
        <ItemTemplate>
            <asp:CheckBox ID="cbSelProduct" runat="server"/>
        </ItemTemplate>
        </asp:TemplateField>
        <asp:BoundField DataField="ProductID" HeaderText="Product ID"/>  
        <asp:BoundField DataField="ProductNumber" HeaderText="Product Number"/>  
        <asp:BoundField DataField="Name" HeaderText="Name"/>  
        <asp:TemplateField HeaderText="Price">
        <ItemTemplate>
            <asp:Label ID="lblListPrice" runat="server" Text='<%#Eval("ListPrice","{0:c}")%>'/>
        </ItemTemplate>
        </asp:TemplateField>
         <asp:TemplateField HeaderText="SubCategory">            
            <ItemTemplate>
                <asp:DropDownList ID="ddlSubCategories" runat="server"></asp:DropDownList>
            </ItemTemplate>
        </asp:TemplateField>        
    </Columns>  
    </asp:GridView>
    

    When page is intially loaded,  select command of sqlDSProducts is executed and products resultset is bound to the gridview. Whenever we try to bind data to the gridRowDataBound fires once for each row as its databound. If you want to handle any data binding related special cases, you do it here. We load subcategories into a dropdownlist. We get the list of available sub categories from Production.ProductSubcategory and will bind it to drop down list.

    protected void gvProducts_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            if (e.Row.DataItem != null)
            {
                //check if is in edit mode
                //if ((e.Row.RowState = DataControlRowState.Normal) > 0)
                {
                    DropDownList ddlSubCategories = (DropDownList)e.Row.FindControl("ddlSubCategories");
                    //Bind subcategories data to dropdownlist 
                    ddlSubCategories.DataTextField = "SubCategoryName";
                    ddlSubCategories.DataValueField = "ProductSubcategoryID";
                    ddlSubCategories.DataSource = RetrieveSubCategories();
                    ddlSubCategories.DataBind();
                    DataRowView dr = e.Row.DataItem as DataRowView;
                    ddlSubCategories.SelectedValue = dr["ProductSubCategoryID"].ToString();
                }
            }
        }
    }
    
    private DataTable RetrieveSubCategories()
    {
        //fetch the connection string from web.config
        string connString =
                ConfigurationManager.ConnectionStrings["Sql"].ConnectionString;
        //SQL statement to fetch entries from products
        string sql = @"Select ProductSubcategoryID, Name as SubCategoryName 
            from Production.ProductSubcategory";
        DataTable dtSubCategories = new DataTable();
        //Open SQL Connection
        using (SqlConnection conn = new SqlConnection(connString))
        {
            conn.Open();
            //Initialize command object
            using (SqlCommand cmd = new SqlCommand(sql, conn))
            {
                SqlDataAdapter adapter = new SqlDataAdapter(cmd);
                //Fill the result set
                adapter.Fill(dtSubCategories);
            }
        }
        return dtSubCategories;
    }
    
    Be Sociable, Share!

    Written by

    Software architect with over 10 years of proven experience in designing & developing n-tier and web based software applications, for Finance, Telecommunication, Manufacturing, Internet and other Commercial industries. He believes that success depends on one's ability to integrate multiple technologies to solve a simple as well as complicated problem.

    View all articles by

    Email : [email protected]