Creating a dynamically populated Grid View

Posted On: In: C#

I haven’t published a post here in what feels like an eternity, I came across a problem recently and wasn’t sure how to go about writing the code, what I had was a form which consisted of a number of drop-down boxes and I needed to get the values of the drop-down boxes into a GridView, then loop that GridView to insert that data into a database.

The problem was I also needed to allow for a row to be removed from the Grid View if the user decided the data selected was no longer required.

The Web Form

I will assume you know how to create a form in Visual Studio mine looked like something like this in HTML

Which should look something like this on the page

I am using Bootstrap for the framework

The form has a button on it called Btn_AddRow which has an on click event of Btn_AddRow_Click, the code for this method looks like this, we will get to that in a moment but essentially we are calling another method when the button is clicked.

The GridView

On the same page, I have an asp GridView control this is where the products that I select from the drop-down list will appear when the button is clicked, On initial page load the GridView will not show up on the page as the flag AutoGenerateColumns is set to false and there is no data bound to the GridView control at this point.

Initialize The Grid

When the page first loads, I need to Initialize the GridView to do this I am going to create a new ViewState called dtSource then create a DataTable which will contain the columns of my Gridview, populating the ViewState with the data table as the source and binding it to the GridView.

Add New Rows

I now need a method to handle the events that will take place when I click the button to add a new row to the GridView.

On Row Deleting

This is the method that will handle the removal of the row from the GridView essentially what is happening here is we are creating a DataTable with the current data from the ViewState then we are getting the Row Index of the row that has been clicked then simply deleting that row and then rebinding the GridView using the DataTable and updating the ViewState.

The Page Load

The Page Load method is where we will handle the Initialization of the GridView, remember that method InitializeGrid I created earlier, this is where that is called.