How can we fetch the data in the table according to the table name entered in the textbox? (in C# or asp.net)

Gökhan C 1 Reputation point
2022-01-10T08:14:00.857+00:00

How can we fetch the data in the table according to the table name entered in the textbox? (in C# or asp.net)
E.g:
(select * from users)
I want to use - textbox.text instead of "users".
Like (select * from textbox.text).

Thank you in advance for your contribution.

Developer technologies C#
0 comments No comments
{count} votes

3 answers

Sort by: Most helpful
  1. Gökhan C 1 Reputation point
    2022-01-10T08:34:06.05+00:00

    -get database table name using textbox for c# or asp.net
    -mysql or mssql

    0 comments No comments

  2. Olaf Helper 47,436 Reputation points
    2022-01-10T08:42:07.383+00:00

    Something like dynamically SQL?

    string sql = "SELECT * FROM " & textBox.Text;
    var cmd = new SqlCommand(sql, conn))
    var reader = cmd.ExecuteReader();
    while (reader.Read())
    {  //...
    

    But it's dangerous because it allows SQL Injection: https://en.wikipedia.org/wiki/SQL_injection

    0 comments No comments

  3. Gökhan C 1 Reputation point
    2022-01-10T09:14:04.213+00:00

    Thank you very much for your suggestions and advice, you have kept me informed.

    By the way, I made some minor changes to the code and now it works.

    string sqlCommand = $"SELECT * FROM {TextBox1.Text}";

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.