You have bigger problems than you think.
The use of
if (!IsPostBack)
and
protected void Page_Load(object sender, EventArgs e)
says "this is a website" - and that means your code will not work in production.
C# code is executed on the Server, never the Client - only Javascript code is ever executed on the client. So when you use MessageBox it shows a dialog on the Server, not the Client - where the user cannot see it. That means the execution of code on the Server will stop and wait for a use several thousand miles away to click an "OK" button that he can't see, and doesn't even know is there. He will not get any error message; all he gets is a frozen website...
It works in development because the Server and the Client are the same physical machine - so when the server shows a dialog you see it it on the Server and it looks like it works. But it doesn't, not realy - and as soon as you get to production, it fails catastrophically.
And given that this is a website, you should not be even trying to "share" an SqlConnection - you must create it it anew each time you use it because they are scarce resources and if you create one and hold it, it can last far too long - even if the client has turned off his machine and gone home! Given that websites are designed to be browsed but multiple users, this can exhaust the supply of connections to SQL pretty quickly, and then users get "Can't connect to server" messages. Or would, if your code didn't use MessageBoxes to display them ... :sigh:
The "Proper" way to do DB access:
using (SqlConnection con = new SqlConnection(strConnect))
{
con.Open();
using (SqlDataAdapter da = new SqlDataAdapter("SELECT MyColumn1, MyColumn2 FROM myTable WHERE mySearchColumn = @SEARCH", con))
{
da.SelectCommand.Parameters.AddWithValue("@SEARCH", myTextBox.Text);
DataTable dt = new DataTable();
da.Fill(dt);
myDataGridView.DataSource = dt;
}
}
Or
using (SqlConnection con = new SqlConnection(strConnect))
{
con.Open();
using (SqlCommand cmd = new SqlCommand("SELECT MyColumn1, MyColumn2 FROM myTable WHERE mySearchColumn = @SEARCH", con))
{
cmd.Parameters.AddWithValue("@SEARCH", myTextBox.Text);
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
int id = (int) reader["Id"];
string desc = (string) reader["description"];
...
}
}
}
}
The
using
block ensures that the objects are Disposed automatically, regardless of what happens.