Search code examples
c#sqlsqldatareadersqlexception

How do I resolve System.Data.SqlClient.SqlException exception


I'm having an issue where I am getting an exception and I'm not sure how to handle it, as I thought I did.

On the reader = command.ExecuteReader() I'm getting the following exception message:

An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code.

There isn't any data to pull through, which is fine, that's why I added the if(reader.HasRows) statement for in case there's no data on page load.

How should I be handling this?

Abbreviated code below:

protected void Page_Load(object sender, EventArgs e)
{
    using (SqlConnection connection = new SqlConnection(
        ConfigurationManager.ConnectionStrings["LocalConnection"].ConnectionString))
    {
        string selectSql = "SELECT tb1,tb2 FROM Stuff INNER JOIN User ON " + 
            "User.Stuff_FK=Stuff.ID";

        using (SqlCommand command = new SqlCommand(selectSql, connection))
        {
            // populate already existing data
            SqlDataReader reader;

            connection.Open();
            reader = command.ExecuteReader();
            if (reader.HasRows)
            {
                while (reader.Read())
                {
                    TB1.Text = reader["tb1"].ToString();
                    TB2.Text = reader["tb2"].ToString();
                }
                reader.Close();
            }
            else
            {
                connection.Close();
            }
        }
    }
}

Solution

  • User is a reserved keyword, you need to wrap it in []:

    string selectSql = "SELECT tb1,tb2 FROM Stuff INNER JOIN [User] ON [User].Stuff_FK=Stuff.ID";
    

    For that reason i would have chosen a different table-name. By the way, Stuff is also a T-SQL function, but that should work anyway if that table exists.