An error has occurred: System.Data.SqlClient.SqlException: SQL Server does not exist or access denied. at System.Data.SqlClient.ConnectionPool.CreateConnection() at System.Data.SqlClient.ConnectionPool.UserCreateRequest() at System.Data.SqlClient.ConnectionPool.GetConnection(Boolean& isInTransaction) at System.Data.SqlClient.SqlConnectionPoolManager.GetPooledConnection(SqlConnectionString options, Boolean& isInTransaction) at System.Data.SqlClient.SqlConnection.Open() at ASP.dynamicdatasource_aspx.BindList()
|
|
|
|
|||||||||||||||
Click here to return to my article index
ASP.NET: Dynamically set Text and Value fields for a DropDownListThis code was written in response to a message posted on one of the ASPAlliance lists. You can sign up for one or all of the lists here.
In this article, we will look at a technique that allows us to switch the value and text represenation of the items in a DropDownList. I know, it's
probably not something you will see in many applications but it is yet another example of the power of ASP.NET.
Code:
<%@ Page Language="VB" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<html>
<script language="VB" runat="server">
Sub Page_Load(sender As Object, e As EventArgs)
If Not IsPostBack Then
DropDownList1.DataTextField = "pub_name"
DropDownList1.DataValueField = "pub_id"
BindList()
End If
End Sub
Sub ButtonClick(sender As Object, e As EventArgs)
If sender.ID = "Button1" Then
DropDownList1.DataTextField = "pub_id"
DropDownList1.DataValueField = "pub_name"
Else
DropDownList1.DataTextField = "pub_name"
DropDownList1.DataValueField = "pub_id"
End If
BindList()
Button1.Visible = "False"
Button2.Visible = "True"
End Sub
Sub BindList()
Dim myConnection As SqlConnection = new SqlConnection(ConfigurationSettings.AppSettings("DSN_pubs"))
Dim myCommand As SqlCommand = new SqlCommand("Select pub_id, pub_name From publishers", myConnection)
Dim myDataReader As SqlDataReader
Try
myConnection.Open()
myDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection)
DropDownList1.DataSource = myDataReader
DropDownList1.DataBind()
Catch myException As Exception
Response.Write("An error has occurred: " & myException.ToString())
Finally
If Not myDataReader Is Nothing Then
myDataReader.Close()
End If
DropDownList1.Items.Insert(0, "Select an Item")
DropDownList1.SelectedIndex = 0
End Try
End Sub
</script>
<body>
<form runat="Server">
<asp:DropDownList id="DropDownList1" runat="server" />
<asp:Button id="Button1" Text="Switch Em" OnClick="ButtonClick" runat="server" />
<asp:Button id="Button2" Text="Switch Em Back" OnClick="ButtonClick" Visible="False" runat="server" />
</form>
</body>
</html>
Result: |