IntroductionSometimes we got some cases when we have two dropdown lists in gridview and want the second one to be populated based on a selection of the first dropdown list.
Here I am going to explain how we can do this.
Here in this example, I am going to create a page for update person details where list of persons showing in a Gridview with the following fields Person ID, Person Name, Address, State, and City.
Here I have used Two dropdown list in this gridview for showing State and City. The second one (City) data populated based on a selection of the first dropdown list (State).
Step-1 : Create New ProjectGo 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 GridviewOpen 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
Step-6: Create a page for show list of person in Gridview.
Gridview Design Code
Write followings code to Page_load event.
Write followings code (function) for populate state.
Write followings code (function) for populate city based on selected state.
private List<CityMaster> populateCity(int stateID)
Write followings code to ddState_SelectedIndexChanged (State dropdown Selected Index Changed) event.
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
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
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