Populate DataTable from SQL Server Database

This is a mystery to me, I know the code that I took from others, in my case the data type returned by them is empty

conSTR - connection string specified as a global string

 public DataTable fillDataTable(string table) { string query = "SELECT * FROM dstut.dbo." +table; SqlConnection sqlConn = new SqlConnection(conSTR); sqlConn.Open(); SqlCommand cmd = new SqlCommand(query, sqlConn); DataTable dt = new DataTable(); dt.Load(cmd.ExecuteReader()); sqlConn.Close(); return dt; } 

EDIT 1
The thing is to later show this table in the datagrid view on tabcontrol, here is the question of displaying multiple data in tabcontrol C #

Here it just shows me an empty datagridview

EDIT 2
Tried all of them, when I try to display the table, datagridview is empty, has the right number of rows, but now the value

+6
source share
2 answers

If the table variable contains invalid characters (such as a space), you must add square brackets around the variable.

 public DataTable fillDataTable(string table) { string query = "SELECT * FROM dstut.dbo.[" + table + "]"; using(SqlConnection sqlConn = new SqlConnection(conSTR)) using(SqlCommand cmd = new SqlCommand(query, sqlConn)) { sqlConn.Open(); DataTable dt = new DataTable(); dt.Load(cmd.ExecuteReader()); return dt; } } 

By the way, be very careful with this code, because it is open for Sql Injection. Hope the table name is not derived from user input

+27
source

Try the following:

 public DataTable fillDataTable(string table) { string query = "SELECT * FROM dstut.dbo." +table; SqlConnection sqlConn = new SqlConnection(conSTR); sqlConn.Open(); SqlCommand cmd = new SqlCommand(query, sqlConn); SqlDataAdapter da=new SqlDataAdapter(cmd); DataTable dt = new DataTable(); da.Fill(dt); sqlConn.Close(); return dt; } 

HopeIts Helpful.

+2
source

Source: https://habr.com/ru/post/946660/


All Articles