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:
CREATE PROCEDURE dbo.proc_MyQuery
AS
SELECT (list of columns)
FROM dbo.MyTable
WHERE (condition)
When you do this, you can create a SqlCommand
in your C# code and call that stored procedure and retrieve the results back.
or:
- you can execute the query directly from your C# code by creating a
SqlConnection
and a SqlCommand
object 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 SqlConnection
to your database, and then a SqlCommand
to 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 a DataTable
. So your code would look something like this:
DataTable resultTable = new DataTable();
using(SqlConnection con = new SqlConnection("your connection string here"))
{
string sqlStmt = "SELECT (columns) FROM dbo.YourTable WHERE (condition)";
using(SqlCommand cmd = new SqlCommand(sqlStmt, con))
{
SqlDataAdapter dap = new SqlDataAdapter(cmd);
dap.Fill(resultTable);
}
}
and then to bind to the gridview, you'd use something like:
myGridView.DataSource = resultTable;
myGridView.DataBind();
and to navigate the DataTable
, you can step through its .Rows()
collection of data rows.