Show DB Tables in DropDownList – Select from Table

Sometimes, we have the need to merely look at the tables from a database, choosing the actual table dynamically. This example shows how to list the Table Names from a SQL Server, in a DropDownList, select from the list, and then shows the results of the table in a DataGrid. (Since these tables are not in separate db in this system, it will show up with ‘NW’ as a prefix to each tablename – naturally, I don’t want to show all of my tables :) .
For a reference, it uses the NorthWind database, so to use it on your page, just copy the code into a new page and change the connection properties.

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SQLClient" %>

<script language="VB" runat="server">
Dim sql as String
Sub Page_Load(Source as Object, E as EventArgs)
if not Page.IsPostBack then
Dim strConn as string = "server=YourServer;uid=UID;pwd=PWD;database=Northwind"
sql = "SELECT [name] FROM sysobjects WHERE xtype=’U’ ORDER BY name"
Dim conn as New SQLConnection(strConn)
Dim Cmd as New SQLCommand(sql, conn)
conn.Open()
ddl.DataSource = Cmd.ExecuteReader(system.data.CommandBehavior.CloseConnection)
ddl.DataBind()
conn.Close
end if
label1.text=""
label1.text=sql
End Sub

Sub getstuff(Source as Object, E as EventArgs)
Dim strConn as string = "server=YourServer;uid=UID;pwd=PWD;database=Northwind"
sql = "Select * from [" & ddl.selecteditem.text & "]"
Dim conn as New SQLConnection(strConn)
Dim Cmd as New SQLCommand(sql, conn)
conn.Open()
MyDataGrid.DataSource = Cmd.ExecuteReader(system.data.CommandBehavior.CloseConnection)
MyDataGrid.DataBind()
conn.close
label1.text=""
label1.text=sql
End Sub
</script>

<Form id="form1" runat="server"> <div align="center"><asp:Label ID="label1" runat="server" /></div>
<br>
<asp:DropDownList id="ddl" datatextfield="name" runat="server" /> <asp:Button id="button1" Text="Get Stuff" onclick="getstuff" runat="server" />
<asp:Datagrid runat="server"
Id="MyDataGrid"
GridLines="Both"
cellpadding="0"
cellspacing="0"
width="100%"
Headerstyle-BackColor="#8080C0"
Headerstyle-Font-Name="Arial"
Headerstyle-Font-Bold="True"
Headerstyle-Font-Size="8"
BackColor="#8080FF"
Font-Name="Arial"
Font-Bold="True"
Font-Size="8"
BorderColor="Black">
</asp:DataGrid>
</Form>

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>