An error has occurred: System.Data.SqlClient.SqlException: SQL Server does not exist or access denied. 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.selectitemindatalist_aspx.BindData()
|
|
|
|
|||||||||||||
Code Snippet - Selecting an Item in a DataList using C#Click here to return to my article index
In this article, we will look at a technique that allows us to generate a DataGrid (children data) based on a selection in a DropDownList (parent data).
Basically, when an item is selected in the DropDownList, the page is posted back and we run a query to fill the DataGrid.
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<html>
<head>
<script language="C#" runat="server">
void Page_Load(Object sender, EventArgs e) {
if (!IsPostBack) {
BindData();
}
}
void BindData() {
SqlConnection myConnection =
new SqlConnection(ConfigurationSettings.AppSettings["DSN_pubs"]);
SqlCommand myCommand =
new SqlCommand("Select title From titles", myConnection);
SqlDataReader myDataReader;
try {
myConnection.Open();
myDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
MyDataList.DataSource = myDataReader;
MyDataList.DataBind();
}
catch (Exception myException) {
Response.Write("An error has occurred: " + myException.ToString());
}
}
void MyDataList_ItemCommand(Object sender, DataListCommandEventArgs e) {
MyDataList.SelectedIndex = e.Item.ItemIndex;
BindData();
}
</script>
</head>
<body>
<form runat="server" method="post">
<asp:DataList id="MyDataList"
runat="server"
Width="100%"
OnItemCommand="MyDataList_ItemCommand"
RepeatColumns="1">
<ItemTemplate>
<asp:Table Runat="server" Width="100%">
<asp:TableRow>
<asp:TableCell>
<asp:LinkButton id="Select" runat="server" Text="Select" CommandName="Select"/>
<asp:Label runat="server" id="lbltitle">
<%#DataBinder.Eval(Container.DataItem, "title") %>
</asp:Label>
</asp:TableCell>
</asp:TableRow>
</asp:Table>
</ItemTemplate>
<SelectedItemTemplate>
<asp:Table Runat="server" Width="100%">
<asp:TableRow BackColor="Yellow">
<asp:TableCell>
<asp:Label runat="server" id="lbltitle2">
<%#DataBinder.Eval(Container.DataItem, "title") %>
</asp:Label>
</asp:TableCell>
</asp:TableRow>
</asp:Table>
</SelectedItemtemplate >
</asp:DataList>
</form>
</body>
</html>
The Result: |