Skip to content Skip to sidebar Skip to footer

Fill Datatable From Sql Server Database

This one is a mystery for me, I know the code I took it from others, in my case the datatable it returns is empty conSTR is the connection string, set as a global string public Dat

Solution 1:

If the variable table contains invalid characters (like a space) you should add square brackets around the variable.

publicDataTablefillDataTable(string table)
{
    string query = "SELECT * FROM dstut.dbo.[" + table + "]";

    using(SqlConnection sqlConn = newSqlConnection(conSTR))
    using(SqlCommand cmd = new SqlCommand(query, sqlConn))
    {
        sqlConn.Open();
        DataTable dt = newDataTable();
        dt.Load(cmd.ExecuteReader());
        return dt;
    }
}

By the way, be very careful with this kind of code because is open to Sql Injection. I hope for you that the table name doesn't come from user input

Solution 2:

Try with following:

public DataTable fillDataTable(string table)
    {
        stringquery="SELECT * FROM dstut.dbo." +table;

        SqlConnectionsqlConn=newSqlConnection(conSTR);
        sqlConn.Open();
        SqlCommandcmd=newSqlCommand(query, sqlConn);
        SqlDataAdapter da=newSqlDataAdapter(cmd);
        DataTabledt=newDataTable();
        da.Fill(dt);
        sqlConn.Close();
        return dt;
    }

Hope it is helpful.

Post a Comment for "Fill Datatable From Sql Server Database"