-3

I want to return a DataTable with this method but SqlParameter is not working properly.

Click Here

private DataTable GetTable(string tableName)
{
        const string queryString = "SELECT * FROM @TABLE";

        SqlCommand sqlCommand = new SqlCommand(queryString, _sqlConnection);

        SqlParameter sqlParameter = new SqlParameter("@TABLE", SqlDbType.Text)
        {
            Value = tableName
        };

        sqlCommand.Parameters.Add(sqlParameter);

        _sqlConnection.Open();

        SqlDataAdapter dataAdapter = new SqlDataAdapter(sqlCommand);
        DataTable dataTable = new DataTable();

        dataAdapter.Fill(dataTable);

        _sqlConnection.Close();
        dataAdapter.Dispose();

        dataGridViewTable.DataSource = dataTable;
        dataGridViewTable.AutoResizeColumns();

        return dataTable;
}

I am sure connection is successful. Another method is working. This one doesn't. It throws a SqlException.

Error description

6
  • 4
    Make sure to provide minimal reproducible example inline in the post as code. Commented Feb 24, 2016 at 17:44
  • 2
    What errors are reported ? Commented Feb 24, 2016 at 17:47
  • 3
    What does “not working properly” mean? It throws an exception? Show it to us. It gives the wrong answer? What does it give? What did you expect? Commented Feb 24, 2016 at 17:49
  • There should be duplicate on using parameter to replace table name (I can't vote to close, jsut wait till someone copy-pastes answers here) - I.e. - stackoverflow.com/questions/17947736/… Commented Feb 24, 2016 at 17:49
  • 1
    Also, you do not need to open/close the connection when you use fill. You pass the connection object to the SqlCommand object, which you have already done. Fill open and closes automatically. Commented Feb 24, 2016 at 18:06

1 Answer 1

2

You can't pass a table name as a parameter. Also, use using to easily close/dispose of disposable resources.

Try this...

private DataTable GetTable(string tableName)
{
    string queryString = "SELECT * FROM [" + tableName + "]";

    DataTable dataTable = new DataTable(tableName);
    using (SqlCommand sqlCommand = new SqlCommand(queryString, _sqlConnection))
    using (SqlDataAdapter dataAdapter = new SqlDataAdapter(sqlCommand))
    {
        _sqlConnection.Open();
        dataAdapter.Fill(dataTable);
        _sqlConnection.Close();
    }
    dataGridViewTable.DataSource = dataTable;
    dataGridViewTable.AutoResizeColumns();
    return dataTable;
}

EDIT: Added square brackets around table name in query to handle names with spaces.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.