Friday, May 25, 2007

How to select all Table Fields or Table Column Names in Asp.net & Sql Server 2000/2005

From many days i was Searching for A Source Code Which can return a Column Name of Selected Table. So Finally After a little bit of Effort i did it.



Here is Code To do it.



Before Using Code please Change Connection String and Give Respactive TableName in CommandText.



VB

Dim dr As SqlDataReader

Dim cmd As SqlCommand = New SqlCommand

Dim conn As SqlConnection = New SqlConnection("Server=Server\sqlexpress;Database=PragatiDataServer;Uid=dev_user;Pwd=password;")

conn.Open

cmd.Connection = conn

cmd.CommandType = CommandType.Text

cmd.CommandText = "select * from table_ads"

dr = cmd.ExecuteReader(CommandBehavior.SchemaOnly)

dr.Read

Dim dt As DataTable = dr.GetSchemaTable

Dim i As Integer = 0

While i < dt.Rows.Count

 Response.Write(dt.Rows(i).ItemArray(0) + "<br>")

 System.Math.Min(System.Threading.Interlocked.Increment(i),i-1)

End While

dr.Close

conn.Close




C#





SqlDataReader dr;

SqlCommand cmd = new SqlCommand();

SqlConnection conn = new
                  SqlConnection("Server=Server\\sqlexpress;Database=PragatiDataServer;Uid=dev_user;Pwd=password;");


conn.Open();

cmd.Connection = conn;

cmd.CommandType = CommandType.Text;

cmd.CommandText = "select * from table_ads";

dr = cmd.ExecuteReader(CommandBehavior.SchemaOnly);

dr.Read();

DataTable dt = dr.GetSchemaTable();

for (int i = 0; i < dt.Rows.Count; i++)

    {


         Response.Write(dt.Rows[i].ItemArray[0] + "<br>");



    }


dr.Close();

conn.Close();









Powered by ScribeFire.

No comments: