none
How to use Table name as a Datatable type. RRS feed

  • Question

  • I am pulling table name from database. I want to use Table name as DataTable type or you can say convert Table name as DataTable. I need table name as DatTable to perform some operation.
    Thursday, December 28, 2017 9:27 AM

Answers

  • Hi AJret,

    If you know the table name, we could not retrieve related records from database and fill it into datatable object.

    public static DataTable GetTableFromTableName(string tableName, string connectionString)
            {
                DataTable dt = new DataTable();
                using (SqlConnection conn = new SqlConnection(connectionString))
                {
                    string sqlText = string.Format("select * from {0}", tableName);
                    using (SqlCommand command = new SqlCommand(sqlText,conn))
                    {
                        conn.Open();
                        SqlDataAdapter adapter = new SqlDataAdapter(command);
                        adapter.Fill(dt);
                    }
                }
                return dt;
            }
    

    Best regards,

    Zhanglong Wu


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    • Marked as answer by AJret Friday, December 29, 2017 5:41 AM
    Friday, December 29, 2017 1:54 AM
    Moderator