ASP.Net/ADO.net Database/DataList

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

asp:datalist: repeat column, repeat directions, gridlines,

<%@ Page Language=VB Debug=true %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.OLEDB" %>
<script runat=server>
Sub Page_Load(ByVal Sender as Object, ByVal E as EventArgs)
    If Not IsPostBack Then
        Dim DBConn as OleDbConnection
        Dim DBCommand As OleDbDataAdapter
        Dim DSPageData as New DataSet
        DBConn = New OleDbConnection( _
            "PROVIDER=Microsoft.Jet.OLEDB.4.0;" _
            & "DATA SOURCE=" _
            & Server.MapPath("EmployeeDatabase.mdb;"))
        DBCommand = New OleDbDataAdapter _
            ("Select FirstName, LastName " _
            & "From Employee " _
            & "Order By FirstName", DBConn)
        DBCommand.Fill(DSPageData, _
            "Employee")
        dlDepts.DataSource = _
            DSPageData.Tables("Employee").DefaultView
        dlDepts.DataBind()
    End If
End Sub
</SCRIPT>
<HTML>
<HEAD>
<TITLE>Creating a Basic DataList Control</TITLE>
</HEAD>
<Body LEFTMARGIN="40">
<form runat="server">
<BR><BR>
<asp:datalist 
    id="dlDepts" 
    runat="server" 
    repeatcolumns=2
    repeatdirection="Vertical"
    repeatlayout="table"
    gridlines="Both"
    backcolor="lightyellow"
    forecolor="darkred"
    borderwidth=3
    bordercolor="darkgreen"
>
    <headerstyle
        backcolor="darkred"
        forecolor="lightyellow"
        font-bold="true"
    />
    <headertemplate>
        Below is a list of all the employees.
    </headertemplate>
    <itemtemplate>
        <%# "<B>Department:</B> " _
            & DataBinder.Eval(Container.DataItem, "FirstName") _
            & "<BR>" _
            & DataBinder.Eval(Container.DataItem, "LastName") 
        %>
    </itemtemplate>
    <alternatingitemstyle
        backcolor="lightgreen"
        forecolor="darkblue"
    />
    <alternatingitemtemplate>
        <%# "<B>Department:</B> " _
            & DataBinder.Eval(Container.DataItem, "FirstName") _
            & "<BR>" _
            & DataBinder.Eval(Container.DataItem, "LastName") 
        %>
    </alternatingitemtemplate>
    <separatortemplate>
        ***
    </separatortemplate>
    <footerstyle
        backcolor="darkred"
        forecolor="lightyellow"
        font-bold="true"
    />
    <footertemplate>
        No more records found.
    </footertemplate>
</asp:datalist>
</form>
</BODY>
</HTML>


<A href="http://www.nfex.ru/Code/ASPDownload/EmployeeDatabase.zip">EmployeeDatabase.zip( 10 k)</a>


Bind data source to asp:DataList

<%@ Page Language="VB" %>
<script runat="server">
        Function AllPublishers() As System.Data.SqlClient.SqlDataReader
            Dim connectionString As String = "server="(local)\NetSDK"; trusted_connection=true; Database="pubs""
            Dim sqlConnection As System.Data.SqlClient.SqlConnection = New System.Data.SqlClient.SqlConnection(connectionString)
    
            Dim queryString As String = "SELECT [publishers].* FROM [publishers]"
            Dim sqlCommand As System.Data.SqlClient.SqlCommand = New System.Data.SqlClient.SqlCommand(queryString, sqlConnection)
    
            sqlConnection.Open
            Dim dataReader As System.Data.SqlClient.SqlDataReader = sqlCommand.ExecuteReader(System.Data.rumandBehavior.CloseConnection)
    
            Return dataReader
        End Function
        
    Sub Page_Load(sender As Object, e As EventArgs)
      Page.DataBind()
    End Sub
</script>
<html>
<head>
</head>
<body>
    <form runat="server">
        <p>
            <asp:CheckBoxList id="CheckBoxList1" runat="server" DataSource="<%# AllPublishers() %>" DataTextField="pub_name" DataValueField="pub_id"></asp:CheckBoxList>
        </p>
        <p>
            <asp:RadioButtonList id="RadioButtonList1" runat="server" DataSource="<%# AllPublishers() %>" DataTextField="pub_name" DataValueField="pub_id"></asp:RadioButtonList>
        </p>
        <p>
            <asp:DropDownList id="DropDownList1" runat="server" DataSource="<%# AllPublishers() %>" DataTextField="pub_name" DataValueField="pub_id"></asp:DropDownList>
        </p>
        <p>
            <asp:ListBox id="ListBox1" runat="server" DataSource="<%# AllPublishers() %>" DataTextField="pub_name" DataValueField="pub_id"></asp:ListBox>
        </p>
        <p>
            <asp:Repeater id="Repeater1" runat="server" DataSource="<%# AllPublishers() %>">
                <HeaderTemplate>
                    <b>Publisher List:</b>
                    <br />
                </HeaderTemplate>
                <ItemTemplate>
                    <%# DataBinder.Eval(Container.DataItem, "pub_name") %> (ID: <%# DataBinder.Eval(Container.DataItem, "pub_id") %>) <font size="-1"><i> <%# DataBinder.Eval(Container.DataItem, "city") %>, <%# DataBinder.Eval(Container.DataItem, "state") %>, <%# DataBinder.Eval(Container.DataItem, "country") %> 
                    <br />
                    </i></font> 
                </ItemTemplate>
            </asp:Repeater>
        </p>
        <p>
            <asp:DataList id="DataList1" runat="server" DataSource="<%# AllPublishers() %>">
                <ItemTemplate>
                    <p>
                        ID: 
                        <asp:Label id="Label6" runat="server" Text="<%# DataBinder.Eval(Container.DataItem, "pub_id") %>"></asp:Label>
                        &nbsp;Name: 
                        <asp:Label id="Label7" runat="server" Text="<%# DataBinder.Eval(Container.DataItem, "pub_name") %>"></asp:Label>
                    </p>
                    <p>
                        Address: 
                        <asp:Label id="Label8" runat="server" Text="<%# DataBinder.Eval(Container.DataItem, "city") %>"></asp:Label>
                        , 
                        <asp:Label id="Label9" runat="server" Text="<%# DataBinder.Eval(Container.DataItem, "state") %>"></asp:Label>
                        , 
                        <asp:Label id="Label10" runat="server" Text="<%# DataBinder.Eval(Container.DataItem, "country") %>"></asp:Label>
                    </p>
                </ItemTemplate>
                <HeaderTemplate>
                    <asp:Label id="Label1" runat="server" Font-Names="Tahoma" Font-Italic="True">List of publishers:</asp:Label>
                    <hr />
                </HeaderTemplate>
                <FooterTemplate>
                    <hr />
                </FooterTemplate>
                <SeparatorTemplate>
                    <hr />
                    <span style="WIDTH: 100%; HEIGHT: 100%"> 
                    <div contenteditable="true" style="PADDING-RIGHT: 8px; PADDING-LEFT: 8px; PADDING-BOTTOM: 8px; WIDTH: 100%; PADDING-TOP: 8px; HEIGHT: 100%"></div>
                    </span> 
                </SeparatorTemplate>
            </asp:DataList>
        </p>
    </form>
</body>
</html>



Bind data to asp:datalist

<%@ Page Language=VB Debug=true %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.OLEDB" %>
<script runat=server>
Sub Page_Load(ByVal Sender as Object, ByVal E as EventArgs)
    If Not IsPostBack Then
        Dim DBConn as OleDbConnection
        Dim DBCommand As OleDbDataAdapter
        Dim DSPageData as New DataSet
        DBConn = New OleDbConnection( _
            "PROVIDER=Microsoft.Jet.OLEDB.4.0;" _
            & "DATA SOURCE=" _
            & Server.MapPath("EmployeeDatabase.mdb;"))
        DBCommand = New OleDbDataAdapter _
            ("Select * " _
            & "From Employee " _
            & "Order By LastName, FirstName", DBConn)
        DBCommand.Fill(DSPageData, _
            "Employee")
        dgEmps.DataSource = _
            DSPageData.Tables("Employee").DefaultView
        dgEmps.DataBind()
    End If
End Sub
</SCRIPT>
<HTML>
<HEAD>
<TITLE>Using Templates with the DataGrid Control</TITLE>
</HEAD>
<Body LEFTMARGIN="40">
<form runat="server">
<BR><BR>
<asp:Label 
    id="lblMessage" 
    Font-Size="12pt"
    Font-Bold="True"
    Font-Name="Lucida Console"
    text="Employee List"
    runat="server"
/>
<BR><BR>
<asp:datagrid
    id="dgEmps" 
    runat="server" 
    autogeneratecolumns="True"
    BorderColor="black"
    CellPadding=3 
    CellSpacing="0"
    Font-Name="Trebuchet MS"
    Font-Size="10pt"
    ForeColor="Black"
    BackColor="Beige" 
    ShowHeader="True"
    ShowFooter="True"
    AlternatingItemStyle-ForeColor="Cornsilk"
    AlternatingItemStyle-BackColor="DarkBlue"
    AlternatingItemStyle-Font-Name="Arial"
    AlternatingItemStyle-Font-Italic="True"
    HeaderStyle-BackColor="Burlywood"
    HeaderStyle-Font-Bold="True"
    FooterStyle-BackColor="Burlywood"
    FooterStyle-Font-Bold="True"
>
</asp:datagrid>
</form>
</BODY>
</HTML>


<A href="http://www.nfex.ru/Code/ASPDownload/EmployeeDatabase.zip">EmployeeDatabase.zip( 10 k)</a>


Bind the Hashtable to the repeater

<%@ Page Language="c#" %>
<script runat="server">
    void Page_Load(Object sender, EventArgs e) {
      Hashtable cardValues = new Hashtable();
    
      cardValues.Add("Two", 20);
      cardValues.Add("Three", 3);
      cardValues.Add("Four", 4);
      cardValues.Add("Five", 5);
      cardValues.Add("Six", 6);
      cardValues.Add("Seven", 7);
      cardValues.Add("Eight", 20);
      cardValues.Add("Nine", 9);
      cardValues.Add("Ten", 10);
    
      rptCardValues.DataSource = cardValues;
      rptCardValues.DataBind();
    }
</script>
<p>
Card values!
<asp:repeater id="rptCardValues" runat="server">
  <HeaderTemplate>
    <ul>
  </HeaderTemplate>
  <ItemTemplate>
    <li><%# DataBinder.Eval(Container.DataItem, "Key") %> -
    <%# DataBinder.Eval(Container.DataItem, "Value") %></li>
  </ItemTemplate>
  <FooterTemplate>
    </ul>
  </FooterTemplate>
</asp:repeater>



datalist and ItemTemplate

<%@ Page %>
<%@ import Namespace="System.Data" %>
<%@ import Namespace="System.Data.SqlClient" %>
<script runat="server">
    Sub Page_Load(sender as Object, e as EventArgs)
       Const strConnString as String = "server=localhost;uid=sa;pwd=;database=pubs"
       Dim objConn as New SqlConnection(strConnString)
    
      Const strSQL as String = "SELECT * FROM authors"
      Dim objCmd as New SqlCommand(strSQL, objConn)
    
      Dim objDA as New SqlDataAdapter()
      objDA.SelectCommand = objCmd
    
      Dim objDS as New DataSet()
      objDA.Fill(objDS)
      objConn.Close()
    
      dlAuthors.DataSource = objDS
      dlAuthors.DataBind()
    End Sub
</script>
<asp:datalist id="dlAuthors" runat="server"
     RepeatColumns="4">
  <ItemTemplate>
    <b><%# DataBinder.Eval(Container.DataItem, "au_lname") %>,
    <%# DataBinder.Eval(Container.DataItem, "au_fname") %></b>
  </ItemTemplate>
</asp:datalist>



DataList data binding with objects

<script language="C#" runat="server">
public class State {
    string _name;
    string _timezone;
    public State(string name, string timezone) {
        _name = name;
        _timezone = timezone;
    }
    public string Name {
        get { return _name; }
    }
    public string TimeZone {
        get { return _timezone; }
    }
}
protected void Page_Load(object o, EventArgs e) {
    if(!IsPostBack) {
        ArrayList states = new ArrayList();
        states.Add(new State("Washington", "Pacific"));
        states.Add(new State("Utah", "Mountain"));
        datalist.DataSource = states;
        datalist.DataBind();
        datalist.SelectedIndex = 0;
    }
}
</script>
<form runat="server">
<asp:DataList 
    runat="server" 
    id="datalist" 
    BackColor="tan"
    RepeatDirection="Vertical" 
    BorderWidth="1"
    BorderColor="Black"
    Repeatcolumns="2" 
    CellSpacing="3"
    CellPadding="4" 
>
<SelectedItemStyle BackColor="red" >
</SelectedItemStyle>
<ItemTemplate>
    <%# DataBinder.Eval(Container.DataItem, "Name") %> is in
    <%# DataBinder.Eval(Container, "DataItem.Timezone") %>
</ItemTemplate>
</asp:DataList>
</form>



LinkButton in ItemTemplate

<%@ Page Language="vb" %>
<%@ import Namespace="System.Data" %>
<%@ import Namespace="System.Data.SqlClient" %>
<script runat="server" language="VB">
    Sub Page_Load(sender as Object, e as EventArgs)
      If Not Page.IsPostBack then
        BindData()
      End If
    End Sub
    
    Sub BindData()
       Const strConnString as String = "server=localhost;uid=sa;pwd=;database=pubs"
       Dim objConn as New SqlConnection(strConnString)
    
       Const strSQL as String = "SELECT * FROM titles"
       Dim objCmd as New SqlCommand(strSQL, objConn)
       objConn.Open()
       dlTitles.DataSource = objCmd.ExecuteReader(CommandBehavior.CloseConnection)
       dlTitles.DataBind()
      objConn.Close()
    End Sub
    
    Sub dlTitles_ItemCommand(sender as Object, e as DataListCommandEventArgs)
      If e.rumandName = "Details" then
      End If
    End Sub
</script>
<form runat="server">
  <asp:DataList runat="server" id="dlTitles"
       OnItemCommand="dlTitles_ItemCommand">
    <ItemTemplate>
      <b>Title:</b> <%# DataBinder.Eval(Container.DataItem, "title") %>
      <br />
      [<asp:LinkButton runat="server" id="btnDetails" 
           Text="View Book Details" CommandName="Details" />]
    </ItemTemplate>
    
    <SeparatorTemplate>
      <hr>
    </SeparatorTemplate>
  </asp:DataList>
</form>



Set the DataSource to a String array of file names

<%@ Page %>
<%@ import Namespace="System.IO" %>
<script runat="server">
    Sub Page_Load(sender as Object, e as EventArgs)
      "Set the DataSource to a String array of file names
      dgFiles.DataSource = Directory.GetFiles("C:\")
      dgFiles.DataBind()
    End Sub
</script>
<asp:datalist id="dgFiles" runat="server"
     RepeatColumns="2" CellSpacing="5">
  <ItemTemplate>
    <%# Container.DataItem %>
  </ItemTemplate>
</asp:datalist>