0

I'm developing a web app using Asp.net webforms. The requirement is to populate a gridview based on selected value from dropdown which I can achieve no problem. What I'm trying to do is minimize my code so I don't have to repeat myself. So I've created a method which returns a DataTable from the query that is passed in as a parameter to that function.

public DataTable GetData(string Query)
{
 //Do stuff i.e. sql reader 
  ...
}

Some of the Sql quesries will have params and others won't e.g.

  1. SELECT TESTONE FROM MY TABLE WHERE TESTONE = @param
  2. SELECT TESTTWO FROM MY TABLE

I want to be able to call GetData() method with both of the above queries but I can't figure out how to extend my function to accommodate for both scenarios. If someone can guide me I would highly appreciate it.

Would using a GetData(string Query, Dictionary<string, object> parameters) be a overkill in this case?

Izzy
  • 6,740
  • 7
  • 40
  • 84
  • No, a `Dictionary parameters` would not be overkill . You might even find a [`List`](https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlparameter(v=vs.110).aspx) to be even better – Rhumborl Mar 01 '16 at 09:58
  • @Rhumborl If I use `Dictionary parameters` how would I call my method for the first query? or would it be possible if you can provide a short example please – Izzy Mar 01 '16 at 10:00

1 Answers1

0

I managed to figure this out by making the following changes to the my code.

public DataTable GetTrainingData(string query, params string[] parameters)
{
 // Do work here
}

I can now call the same method for both of my queries as

  1. GetTrainingData("SqlQuery")
  2. GetTrainingData("SqlQuery", parameters)

Further reading on params key word here and here

Community
  • 1
  • 1
Izzy
  • 6,740
  • 7
  • 40
  • 84