Friday, 29 November 2013

How to update sql database when you don't want to hard code the column names in the application

One of my first applications I was asked to do was an intranet based reporting tool and my customer was a software department. I wasn't given many constraints apart from that it would have to be a ASP.Net application and nothing project specific should be hard coded into the web application to allow multiple uses for the same page. I quickly realized that the gridview control in ASP.Net would make the perfect control for showing and allowing for editing of the data regarding the projects. Pretty much all the coding was done in the C# "code behind" of the application with the .aspx page containing only the named control linked up with the event methods in the code behind where all the data binding and formatting was taking place.

It was relatively easy to produce a nice looking table retrieved from the sql database in the gridview but how would I go about saving any changes without specifying any columns names in the code? It turned out it wasn't so hard after all as the information was already known to the application as the column names were present in the gridview as the gridview column names and the data to be saved was in the data row below.

In the GridView1_RowUpdating event I stored the column names and the data in two lists as shown below:

Code here
In the sql update method I first created the sql string with the column name information and made sure that every update was made using parameters to avoid the risk of sql injection. The data was then taken from the second list and added in the Parameters.AddWithValue function and the sql query was executed.

Code here

For this to work you need to have all your data in one database table but you don't necessarily have to show (or update) the whole table. Also if you have different names for your columns in the gridview compared to your column names in your database table you could potentially just create a look up table in the database and call this for each name in the list of column names before calling the sql updating method.

No comments:

Post a Comment