Sunday, August 11, 2019

Implementing cascading DropDownList in GridView in ASP.NET with out Web Service, Ajax

Step-1 : Create New Project

Go to File > New > Project > Select asp.net web forms application > Entry Application Name > Click OK.

Step-2: Add a Database.

Go to Solution Explorer > Right Click on App_Data folder > Add > New item > Select SQL Server Database Under Data > Enter Database name > Add.

Step-3: Create a table and insert data for show in Gridview

Open Database > Right Click on Table > Add New Table > Add Columns > Save > Enter table name > Ok.

Step-4: Add Entity Data Model.

Go to Solution Explorer > Right Click on Project name form Solution Explorer > Add > New item > Select ADO.net Entity Data Model under data > Enter model name > Add.
A popup window will come (Entity Data Model Wizard) > Select Generate from database > Next >
Chose your data connection > select your database > next > Select tables > enter Model Namespace > Finish.

Step-5: Create a Partial class of PersonMaster.

Right click on Folder(your class container) from solution explorer > Add > Class > Enter Class name > Add.
This is required for get Person details with StateName and CityName in a single Entity Set which is from different tables.
Here is the complete code 


public partial class PersonMaster
    {
        public string StateName { getset; }
        public string CityName { getset; }

    }

Step-6: Create a page for show list of person in Gridview.


Gridview Design Code

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" BackColor="White" BorderColor="#CC9966" BorderStyle="None" BorderWidth="1px"  CellPadding="4" onrowediting="GridView1_RowEditing"  DataKeyNames="StateID,CityID,PersonID"
           onrowcancelingedit="GridView1_RowCancelingEdit"
           onrowupdating="GridView1_RowUpdating">
        <Columns>
            <asp:TemplateField HeaderText="Person Details">
                <ItemTemplate>
                    <table border="0" cellpadding="0" cellspacing="5">
                        <tr>
                            <td>Person Name : </td>
                            <td>
                                <%#Eval("PersonName"%>
                            </td>
                        </tr>
                        <tr>
                            <td>Address : </td>
                            <td>
                                <%#Eval("Address"%>
                            </td>
                        </tr>
                        <tr>
                            <td>State : </td>
                            <td>
                                <%#Eval("StateName"%>
                            </td>
                        </tr>
                        <tr>
                            <td>City : </td>
                            <td>
                                <%#Eval("CityName"%>
                            </td>
                        </tr>
                        <tr>
                            <td></td>
                            <td>
                                <asp:LinkButton ID="lbtnEdit" runat="server" Text="Edit"CommandName="Edit" CommandArgument='<%#Eval("PersonID"%>'/>
                            </td>
                        </tr>
                    </table>
                </ItemTemplate>
                 <EditItemTemplate>
                    <table border="0" cellpadding="0" cellspacing="5">
                        <tr>
                            <td>Person Name : </td>
                            <td>
                                <asp:TextBox ID="txtPersonName" runat="server"Text='<%#Eval("PersonName"%>'></asp:TextBox>
                            </td>
                        </tr>
                        <tr>
                            <td>Address : </td>
                            <td>
                                 <asp:TextBox ID="txtAddress" runat="server" Text='<%#Eval("Address")%>'></asp:TextBox>
                            </td>
                        </tr>
                        <tr>
                            <td>State : </td>
                            <td>
                                <asp:DropDownList ID="ddState" DataTextField="StateName"DataValueField="StateID"
                                    runat="server" AutoPostBack="true"onselectedindexchanged="ddState_SelectedIndexChanged" >                                   
                                </asp:DropDownList>
                            </td>
                        </tr>
                        <tr>
                            <td>City : </td>
                            <td>
                                <asp:DropDownList ID="ddCity" runat="server" DataTextField="CityName"DataValueField="CityID">
                                   
                                </asp:DropDownList>
                            </td>
                        </tr>
                        <tr>
                            <td>
                                <asp:LinkButton ID="lbtnUpdate" runat="server" Text="Update"CommandName="Update"
                                    CommandArgument='<%#Eval("PersonID"%>'/>
                            </td>
                            <td>
                                <asp:LinkButton ID="lbtnCancel" runat="server" Text="Cancel"CommandName="Cancel" />
                            </td>
                        </tr>
                    </table>
                </EditItemTemplate>
            </asp:TemplateField>
        </Columns>
           <FooterStyle BackColor="#FFFFCC" ForeColor="#330099" />
           <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="#FFFFCC" />


<PagerStyle BackColor="#FFFFCC" ForeColor="#330099" HorizontalAlign="Center" />
           <RowStyle BackColor="White" ForeColor="#330099" />
           <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="#663399" />
           <SortedAscendingCellStyle BackColor="#FEFCEB" />
           <SortedAscendingHeaderStyle BackColor="#AF0101" />
           <SortedDescendingCellStyle BackColor="#F6F0C0" />
           <SortedDescendingHeaderStyle BackColor="#7E0000" />
       </asp:GridView>

Write followings code to Page_load event.

protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                populateData();
            }

        }

This is the populateData function

private void populateData()
        {
            // here code for populate person data
            using (MyDatabaseEntities dc = new MyDatabaseEntities())
            {
                var v = (from p in dc.PersonMasters
                         join s in dc.StateMasters on p.StateID equals s.StateID
                         join c in dc.CityMasters on p.CityID equals c.CityID
                         select new


                         {
                             p,
                             s.StateName,
                             c.CityName
                         });
                List<PersonMaster> allP = new List<PersonMaster>();
                foreach (var i in v)
                {
                    PersonMaster p = new PersonMaster();
                    p = i.p;
                    p.StateName = i.StateName;
                    p.CityName = i.CityName;
                    allP.Add(p);
                }

                GridView1.DataSource = allP;
                GridView1.DataBind();
            }
        }

Write followings code (function) for populate state.

private List<StateMaster> populateState()
        {
            // here code for populate state
            List<StateMaster> all = new List<StateMaster>();
            using (MyDatabaseEntities dc = new MyDatabaseEntities())
            {
                all = dc.StateMasters.ToList();
            }
            return all;

        }

Write followings code (function) for populate city based on selected state.

  private List<CityMaster> populateCity(int stateID)
        {
            // here code for populate city based on stateID
            List<CityMaster> all = new List<CityMaster>();
            using (MyDatabaseEntities dc = new MyDatabaseEntities())
            {
                all = dc.CityMasters.Where(a => a.StateID.Equals(stateID)).ToList();
            }
            return all;
        }

Write followings code to ddState_SelectedIndexChanged (State dropdown Selected Index Changed) event.

protected void ddState_SelectedIndexChanged(object sender, EventArgs e)
        {
            // Populate city
            string stateID = ((DropDownList)sender).SelectedValue;
            int rowIndex = GridView1.EditIndex;
            DropDownList ddCityEdit = (DropDownList)GridView1.Rows[rowIndex].FindControl("ddCity");
            if (ddCityEdit != null)
            {
                var v = populateCity(Convert.ToInt32(stateID));
                ddCityEdit.DataSource = v;
                ddCityEdit.DataBind();
                if (ddCityEdit.Items.Count > 0)
                {
                    ddCityEdit.SelectedIndex = 0;
                }
            }
        }

Step-7: Create event for Gridview Editing (GridView1_RowEditing) and write following code.

Select Gridview from design page > go to Properties Window > Double click on RowEditing form Enevts List


Write followings code to GridView1_RowEditing event 


protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
        {
            string stateID = GridView1.DataKeys[e.NewEditIndex]["StateID"].ToString();
            string cityID = GridView1.DataKeys[e.NewEditIndex]["CityID"].ToString();
            // Edit Event
            GridView1.EditIndex = e.NewEditIndex;
            populateData();

            // Here populate data for dropdown state
            DropDownList ddStateEdit = (DropDownList)GridView1.Rows[e.NewEditIndex].FindControl("ddState");
            if (ddStateEdit != null)
            {
                ddStateEdit.DataSource = populateState();
                ddStateEdit.DataTextField = "StateName";
                ddStateEdit.DataValueField = "StateID";
                ddStateEdit.DataBind();
                ddStateEdit.SelectedValue = stateID;
            }
           
            DropDownList ddCityEdit = (DropDownList)GridView1.Rows[e.NewEditIndex].FindControl("ddCity");
            if (ddCityEdit != null)
            {
                ddCityEdit.DataSource = populateCity(Convert.ToInt32(stateID));
                ddCityEdit.DataTextField = "CityName";
                ddCityEdit.DataValueField = "CityID";
                ddCityEdit.DataBind();
                ddCityEdit.SelectedValue = cityID;
            }


        }

Step-8: Create event for Gridview Cancel Editing (GridView1_RowCancelingEdit) and write following code.

Select Gridview from design page > go to Properties Window > Double click on RowCancelingEdit form Enevts List
Write followings code to GridView1_RowCancelingEdit event 



protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            GridView1.EditIndex = -1;
            populateData();

        }

Step-9: Create event for Gridview Updating (GridView1_RowUpdating) and write following code.

Select Gridview from design page > go to Properties Window > Double click on RowUpdating form Enevts List
Write followings code to GridView1_RowUpdating event 


protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            // Here Update
            int personID =Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values["PersonID"].ToString());
            DropDownList ddStateEdit = (DropDownList)GridView1.Rows[e.RowIndex].FindControl("ddState");
            DropDownList ddCityEdit = (DropDownList)GridView1.Rows[e.RowIndex].FindControl("ddCity");
            TextBox txtPersonNameEdit = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtPersonName");
            TextBox txtAddressEdit = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtAddress");

            using (MyDatabaseEntities dc = new MyDatabaseEntities())
            {
                PersonMaster p = dc.PersonMasters.Where(a => a.PersonID.Equals(personID)).FirstOrDefault();
                if (p != null)
                {
                    p.PersonName = txtPersonNameEdit.Text.Trim();
                    p.Address = txtAddressEdit.Text.Trim();
                    p.StateID = Convert.ToInt32(ddStateEdit.SelectedValue);
                    p.CityID = Convert.ToInt32(ddCityEdit.SelectedValue);
                    dc.SaveChanges();
                    GridView1.EditIndex = -1;
                    populateData();
                }
            }

        }

Step-10: Run Application

No comments:

Post a Comment

How to register multiple implementations of the same interface in Asp.Net Core?

 Problem: I have services that are derived from the same interface. public interface IService { } public class ServiceA : IService { ...