Friday, June 12, 2015

Change dropdownlist value on selection of another dropdownlist in gridview



Introduction:
In my previous article, I explained DropDown With Checkboxlist
This article will describe Change dropdownlist value on selection of another dropdownlist in gridview.
Sometime you need two dropdownlist in gridview and one must be rebind on selection of another. I.e. Employee-Department, State-City, Subject-faculty etc.
Description:
In this article, I will show two dropdown one for state and another is for city. Once we select state, other dropdown will rebind again.
Before you continue, first of all we will create two tables, tblState and tblCity, in database and fill some data into respective tables as shown below.
State_Id
StateName

City_Id
City_name
State_id
1
Andhra Pradesh

1
Hyderabad
1
2
Assam

2
Tirupati
1
3
Bihar

3
Visakhapatnam
1
4
Chhattisgarh

4
Dispur
2
5
Goa

5
Patna
3
6
Gujarat

6
Nalanda
3
7
Haryana

7
Raipur
4
8
Himachal Pradesh

8
Panaji
5



9
Ahmedabad
6




Now write code in your aspx page as shown below.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="UpdateDropdown.aspx.cs" Inherits="Test. UpdateDropdown " %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Change dropdownlist value on selection of another dropdownlist in gridview
    </title>
    <style>
        #gvStateWithCity th
        {
            background-color: #3a4078;
            color: #ffffff;
            font-size: 14px !important;
            font-weight: bold !important;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <table width="100%" cellpadding="0" cellspacing="0" border="0">
        <tr>
            <td align="left" valign="top">
                <b>Change dropdownlist value on selection of another dropdownlist in gridview</b><br />
                <br />
                <asp:GridView ID="gvStateWithCity" runat="Server" AutoGenerateColumns="false" AutoGenerateEditButton="false" backcolor="#ececec"
                    RowStyle-Height="32px" OnRowDataBound="gvStateWithCity_RowDataBound" OnRowCancelingEdit="gvStateWithCity_RowCancelingEdit"
                    OnRowEditing="gvStateWithCity_RowEditing" Width="40%">
                    <AlternatingRowStyle backcolor="white" />
                    <EditRowStyle BackColor="lightblue" />
                    <Columns>
                        <asp:TemplateField ShowHeader="true" HeaderText="#">
                            <HeaderStyle Font-Underline="false" HorizontalAlign="center" Width="1%" />
                            <ItemStyle HorizontalAlign="center" />
                            <ItemTemplate>
                                <%# Container.DataItemIndex + 1%>.
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField ShowHeader="true" HeaderText="State Name">
                            <HeaderStyle Font-Underline="false" HorizontalAlign="Center" Width="5%" />
                            <ItemStyle HorizontalAlign="Left" />
                            <EditItemTemplate>
                                <asp:DropDownList ID="ddlStateName" runat="server" AutoPostBack="True" Width="150px" OnSelectedIndexChanged="ddlStateName_SelectedIndexChanged">
                                </asp:DropDownList>
                            </EditItemTemplate>
                            <ItemTemplate>
                                <%# DataBinder.Eval(Container.DataItem, "StateName")%>
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField ShowHeader="true" HeaderText="City Name">
                            <HeaderStyle Font-Underline="false" HorizontalAlign="Center" Width="5%" />
                            <ItemStyle HorizontalAlign="Left" />
                            <EditItemTemplate>
                                <asp:DropDownList ID="ddlCityName" runat="server" Width="150px">
                                </asp:DropDownList>
                            </EditItemTemplate>
                            <ItemTemplate>
                                <%# DataBinder.Eval(Container.DataItem, "City_Name")%>
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:TemplateField ShowHeader="true" HeaderText="Functions">
                            <HeaderStyle Font-Underline="false" HorizontalAlign="Center" Width="3%" />
                            <ItemStyle HorizontalAlign="Center" />
                            <EditItemTemplate>
                                <asp:LinkButton ID="lnkCancel" runat="server" CommandName="Cancel" ToolTip="Cancel"
                                    Text="Cancel" />
                                <asp:Label ID="lblCity_Id" Text='<%# DataBinder.Eval(Container.DataItem, "City_Id")%>'
                                    Visible="false" runat="server"></asp:Label>
                                <asp:Label ID="lblState_Id" Text='<%# DataBinder.Eval(Container.DataItem, "State_Id")%>'
                                    Visible="false" runat="server"></asp:Label>
                            </EditItemTemplate>
                            <ItemTemplate>
                                <asp:LinkButton ID="lnkEdit" CommandName="Edit" runat="server" ToolTip="Edit" Text="Edit" />
                            </ItemTemplate>
                        </asp:TemplateField>
                    </Columns>
                </asp:GridView>
            </td>
        </tr>
    </table>
    </form>
</body>
</html>

Once you finish your aspx page design, let’s complete code behind.
Add Following namespace in your cs page.
C# Code:
using System;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI.WebControls;

First of all we bind gridview and after then we will use its three events i.e. RowDataBound, RowCancelingEdit, RowEditing.

public partial class ManageSkill : System.Web.UI.Page
    {
        static DataSet dsTemp;
        SqlConnection con = new SqlConnection("Data Source=TempDB;Initial Catalog=tem;User ID=user; Password=dbPass;");
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
                GetStateWithCity();
        }

        /// <summary>
        /// This fuction is used to bind gridview
        /// </summary>
        private void GetStateWithCity()
        {
            dsTemp = new DataSet();
            con.Open();
            SqlCommand cmd = new SqlCommand("SELECT S.State_Id, S.StateName,C.City_Id,C.City_Name FROM tbl_City C INNER JOIN tbl_State S on C.State_Id = S.State_Id; SELECT State_id,Statename FROM tbl_State", con);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            da.Fill(dsTemp);

            if (dsTemp.Tables != null)
            {
                gvStateWithCity.DataSource = dsTemp.Tables[0];
                gvStateWithCity.DataBind();
            }
            con.Close();
        }

        /// <summary>
        /// This is rowdatabound event of gridview that binds dropdownlist of every row
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void gvStateWithCity_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            DataRow[] dr;
            if (e.Row.RowType == DataControlRowType.DataRow && gvStateWithCity.EditIndex == e.Row.RowIndex)
            {
                string strCity_Id = ((Label)e.Row.FindControl("lblCity_Id")).Text;
                string strState_Id = ((Label)e.Row.FindControl("lblState_Id")).Text;
                DropDownList ddlStateName = (DropDownList)e.Row.FindControl("ddlStateName");
                DropDownList ddlCityName = (DropDownList)e.Row.FindControl("ddlCityName");
                if (dsTemp.Tables != null)
                {
                    foreach (DataRow dRow in dsTemp.Tables[1].Rows)
                        ddlStateName.Items.Add(new ListItem(dRow["StateName"].ToString().Trim(), dRow["State_Id"].ToString().Trim()));

                    ddlStateName.SelectedValue = strState_Id;
                    dr = dsTemp.Tables[0].Select("State_Id = " + ddlStateName.SelectedValue);
                    foreach (DataRow dRow in dr)
                        ddlCityName.Items.Add(new ListItem(dRow["City_Name"].ToString().Trim(), dRow["City_Id"].ToString().Trim()));

                    ddlCityName.SelectedValue = strCity_Id;
                }
            }
        }

        /// <summary>
        /// This vent will occur when a row's Edit button is clicked, but before the GridView control enters edit mode.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void gvStateWithCity_RowEditing(object sender, GridViewEditEventArgs e)
        {
            gvStateWithCity.EditIndex = e.NewEditIndex;
            GetStateWithCity();
        }

        /// <summary>
        /// This event will occur when the Cancel button of a row in edit mode is clicked, but before the row exits edit mode.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void gvStateWithCity_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            gvStateWithCity.EditIndex = -1;
            if (dsTemp.Tables != null)
            {
                gvStateWithCity.DataSource = dsTemp.Tables[0];
                gvStateWithCity.DataBind();
            }
            else
                GetStateWithCity();
        }

        /// <summary>
        /// This is first dropdownlist in gridview
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ddlStateName_SelectedIndexChanged(object sender, EventArgs e)
        {
            DropDownList ddlStateName = (DropDownList)sender;
            GridViewRow row = (GridViewRow)ddlStateName.Parent.Parent;
            DataRow[] dr;
            DropDownList ddlCityName = (DropDownList)row.Cells[0].FindControl("ddlCityName");
            ddlCityName.Items.Clear();
            if (dsTemp.Tables[0].Rows.Count > 0)
            {
                dr = dsTemp.Tables[0].Select("State_Id = " + ddlStateName.SelectedValue);
                if (dr.Length > 0)
                {
                    foreach (DataRow dRow in dr)
                        ddlCityName.Items.Add(new ListItem(dRow["City_Name"].ToString().Trim(), dRow["City_Id"].ToString().Trim()));
                }
                else
                    ddlCityName.Items.Add(new ListItem("N/A", "N/A"));
            }
        }
    }

Demo:







No comments: