I am using the followng code to bind to an ASP.NET DataGrid. I have the following and it works but wondering if this is the best approach. Few things that concern me is that I did not nee to Open the connection and also I did not make use of the DataReader. Note that this is written in my code behind page.
string strConn = ConfigurationManager.ConnectionStrings["SQL1"].ConnectionString;
SqlDataSource DataSource1 = new SqlDataSource();
DataSource1.ConnectionString = strConn;
DataSource1.SelectCommand = "SELECT * FROM tblTruck where LocId = @LocID ";
DataSource1.SelectParameters.Add(new Parameter("LocId", System.TypeCode.String, value));
Grid1.DataSource = DataSource1.Select(DataSourceSelectArguments.Empty);
Grid1.Rebind();
In this case the DataSource control handles the internal logic of establishing a connection, reading off it, and parsing the return. this in itself is very handy, but causes problems if you need more control.
Stylistically, it is never ever a good idea to have SQL code hardcoded in your UI, though it is good you are using a parameter instead of concatenating.
overall there is no “best approach”. based on factors like maintenance/change, code vulnerability, performance, reliability, display complexity, etc, your solution should be tailored to your problem.
Personally I don’t like datasource controls, but they can be useful for grid work when you don’t want to spend a lot of time configuring the grid.
SQLCommands are very very fast and optimal, but you have to write an maintain a lot of code to use them, and it can be somewhat brittle.
DataAdapters/DataReaders/DataTables/DataSets are somewhat easier to write an maintain than SQLCommands, but they can be cumbersom in memory, and often don’t dispose correctly.
Linq/ENF both make writing and maintaining easy, but sometimes they leave you debugging issues with their own generated sql rather than your own, and are generally slower at execution (often by a not-insignifigant amount).
Hope that helps answer your question.