For my database I create a new query and wrote
select * from dbname
using SQL Server Management Studio Express 2005. Saved it by name SQLQuery1.sql on the desktop.
Now I would like to call this query from C# code when an ASP.NET button is clicked and display the results in a gridview.
How do I call the query? Can I tell Visual Studio 2008 to please execute the query stored in ‘sqlquery1.sql’ ?
Where do I store the results so that I can bind them the display controls like a gridview, or traverse the data?
This is a website in C#, ASP.NET, Visual Studio 2008, and database is on the same computer using SQL Server 2005 Express
You cannot just execute a SQL script you stored on your computer’s desktop from an ASP.NET website.
You can either:
turn your query into a stored procedure in SQL Server, something like:
When you do this, you can create a
SqlCommandin your C# code and call that stored procedure and retrieve the results back.or:
SqlConnectionand aSqlCommandobject and running that SQL statement.These are both absolutely basic ADO.NET features – you should find tons of learning resources online for this.
For instance:
Which ever way you go, you basically need to have a
SqlConnectionto your database, and then aSqlCommandto execute the query. If you want to store the data so you can both bind it to a Gridview as well as navigate it in code, you probably want to store it in aDataTable. So your code would look something like this:and then to bind to the gridview, you’d use something like:
and to navigate the
DataTable, you can step through its.Rows()collection of data rows.