Click here to Skip to main content
15,902,299 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How can we fetch the data in the database 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).

What I have tried:

select * from '"+textbox.text+"' --> does not work
Posted
Updated 9-Jan-22 22:12pm
v3

You can ... it's not even difficult - but it's a very, very bad idea. Let me explain why first ... you should never concatenate strings to build a SQL command. It leaves you wide open to accidental or deliberate SQL Injection attack which can destroy your entire database. Always use Parameterized queries instead.

When you concatenate strings, you cause problems because SQL receives commands like:
SQL
SELECT * FROM MyTable WHERE StreetAddress = 'Baker's Wood'
The quote the user added terminates the string as far as SQL is concerned and you get problems. But it could be worse. If I come along and type this instead: "x';DROP TABLE MyTable;--" Then SQL receives a very different command:
SQL
SELECT * FROM MyTable WHERE StreetAddress = 'x';DROP TABLE MyTable;--'
Which SQL sees as three separate commands:
SQL
SELECT * FROM MyTable WHERE StreetAddress = 'x';
A perfectly valid SELECT
SQL
DROP TABLE MyTable;
A perfectly valid "delete the table" command
SQL
--'
And everything else is a comment.
So it does: selects any matching rows, deletes the table from the DB, and ignores anything else.

So ALWAYS use parameterized queries! Or be prepared to restore your DB from backup frequently. You do take backups regularly, don't you?

Now, your idea does the same thing: I can type in the textbox anything I like:
Students);DROP TABLE Students;--
Will do the same thing: select the rows and return them, then delete the table.

So ... just because you can do it, doesn't mean you should - and you'll need to add some serious protection and validation on the textbox data or you will lose your DB.

but it's simple to do that:
C#
string sqlCommand = $"SELECT * FROM {MyTextBox.Text}";
Will happily let anyone with access to the computer do exactly what they want with your DB.

I'd strongly recommend you don't proceed with this.
 
Share this answer
 
Thank you very much for your suggestions and advice, you have kept me informed.

By the way I tried the code and it works.
Thanks again
 
Share this answer
 
Comments
Richard Deeming 10-Jan-22 5:07am    
If you want to reply to a solution, click the "Have a Question or Comment?" button under the solution and post a comment.

Do not post your comment as another "solution" to the question.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900