ASP.Net/Data Binding/TemplateField — различия между версиями

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

Текущая версия на 11:52, 26 мая 2010

Displaying Column Summaries

<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<script runat="server">
    private decimal _totals = 0;
    protected void grdProducts_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            decimal totals = (decimal)DataBinder.Eval(e.Row.DataItem, "BoxOfficeTotals");
            _totals += totals;
        }
        if (e.Row.RowType == DataControlRowType.Footer)
        {
            Label lblSummary = (Label)e.Row.FindControl("lblSummary");
            lblSummary.Text = String.Format("Total: {0:c}", _totals);
        }
    }
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>Summary Column</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:GridView
        id="grdProducts"
        DataSourceID="srcProducts"
        OnRowDataBound="grdProducts_RowDataBound"
        AutoGenerateColumns="false"
        ShowFooter="true"
        Runat="server">
        <Columns>
        <asp:BoundField
            DataField="Title"
            HeaderText="Title" />
        <asp:TemplateField HeaderText="Box Office Totals">
        <ItemTemplate>
            <%# Eval("BoxOfficeTotals", "{0:c}") %>
        </ItemTemplate>
        <FooterTemplate>
            <asp:Label
                id="lblSummary"
                Runat="server" />
        </FooterTemplate>
        </asp:TemplateField>
        </Columns>
    </asp:GridView>
    <asp:SqlDataSource
        id="srcProducts"
        ConnectionString="<%$ ConnectionStrings:Products %>"
        SelectCommand="SELECT * FROM Products"
        Runat="server" />
    </div>
    </form>
</body>
</html>

File: Web.config
<configuration>
  <connectionStrings>
    <add name="Products" 
         connectionString="Data Source=.\SQLEXPRESS;
         AttachDbFilename=|DataDirectory|MyDatabase.mdf;Integrated Security=True;User Instance=True" />
  </connectionStrings>
</configuration>



Displaying Nested Master/Details Forms

<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<script runat="server">
    protected void grdProductCategories_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            int categoryId = (int)DataBinder.Eval(e.Row.DataItem,"Id");
            SqlDataSource srcProducts = (SqlDataSource)e.Row.FindControl("srcProducts");
            srcProducts.SelectParameters["CategoryId"].DefaultValue = categoryId.ToString();
        }
    }
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<body>
    <form id="form1" runat="server">
    <div>
    <asp:GridView
        id="grdProducts"
        DataSourceID="srcProductCategories"
        OnRowDataBound="grdProductCategories_RowDataBound"
        AutoGenerateColumns="false"
        CssClass="categories"
        ShowHeader="false"
        GridLines="none"
        Runat="server">
        <Columns>
        <asp:TemplateField>
        <ItemTemplate>
            <h1><%# Eval("Name") %></h1>
            <asp:GridView
                id="grdProducts"
                DataSourceId="srcProducts"
                CssClass="Products"
                GridLines="none"
                Runat="server" />
            <asp:SqlDataSource
                id="srcProducts"
                ConnectionString="<%$ ConnectionStrings:Products %>"
                SelectCommand="SELECT Title,Director FROM Products
                    WHERE CategoryId=@CategoryId"
                Runat="server">
                <SelectParameters>
                    <asp:Parameter Name="CategoryId" />
                </SelectParameters>
            </asp:SqlDataSource>
        </ItemTemplate>
        </asp:TemplateField>
        </Columns>
    </asp:GridView>
    <asp:SqlDataSource
        id="srcProductCategories"
        ConnectionString="<%$ ConnectionStrings:Products %>"
        SelectCommand="SELECT Id,Name FROM ProductCategories"
        Runat="server" />
    </div>
    </form>
</body>
</html>

File: Web.config
<configuration>
  <connectionStrings>
    <add name="Products" 
         connectionString="Data Source=.\SQLEXPRESS;
         AttachDbFilename=|DataDirectory|MyDatabase.mdf;Integrated Security=True;User Instance=True" />
  </connectionStrings>
</configuration>



Editing Data using Templated Columns

<%@ Page Language="C#" %>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Editing Data using Templated Columns</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:SqlDataSource ID="productsSource" runat="server"
            ProviderName="System.Data.SqlClient" 
            ConnectionString="<%$ ConnectionStrings:AdventureWorks %>"
            SelectCommand="Select ProductID, Name, ProductNumber, DaysToManufacture, SellStartDate, ReorderPoint from Production.Product"            
            UpdateCommand="Update Production.Product Set ReorderPoint = @ReorderPoint Where ProductID = @ProductID">            
        </asp:SqlDataSource>
       <asp:GridView ID="gridProducts" runat="server" DataSourceID="productsSource"
            AutoGenerateColumns="False" DataKeyNames="ProductID">              
            <Columns>
                <asp:CommandField ShowEditButton="true" />
                <asp:TemplateField HeaderText="Products">
                    <ItemTemplate>                        
                            <%# Eval("ProductID") %> -
                            <%# Eval("Name") %>                            
                             Product Number: <%# Eval("ProductNumber") %><br />                                 
                            Reorder Point:<%# Eval("ReorderPoint") %><br />
                        </small>
                    </ItemTemplate>
                    <EditItemTemplate>
                            <%# Eval("ProductID") %> -
                            <%# Eval("Name") %>                            
                                  Product Number: <%# Eval("ProductNumber") %><br />                                 
                            Reorder Point:<asp:TextBox Text="<%# Bind("ReorderPoint") %>" runat="server" id="textBox"/>
                        </small>
                    </EditItemTemplate>
                </asp:TemplateField> 
            </Columns>
       </asp:GridView>
    </div>
    </form>
</body>
</html>



GridView with Template and backend code

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="GridViewTemplates2" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:SqlDataSource ID="sourceProducts" 
                           runat="server" 
                           ConnectionString="<%$ ConnectionStrings:Northwind %>"
                           ProviderName="System.Data.SqlClient" 
                           SelectCommand="SELECT ProductID, ProductName, UnitPrice, UnitsInStock FROM Products">
        </asp:SqlDataSource>
        <asp:GridView ID="GridView1" 
                      runat="server" 
                      AutoGenerateColumns="False" 
                      CellPadding="4"
                      DataKeyNames="ProductID" 
                      DataSourceID="sourceProducts" 
                      Font-Names="Verdana" 
                      Font-Size="Small" 
                      ForeColor="#333333" 
                      GridLines="None" 
                      AllowPaging="True" 
                      OnRowCommand="GridView1_RowCommand">
            <FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
            <RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
            <PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />
            <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
            <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
            <AlternatingRowStyle BackColor="White" />
            <Columns>
                <asp:TemplateField HeaderText="Status">
                <ItemTemplate>
                    <asp:ImageButton ID="ImageButton1" runat="server" 
                                     ImageUrl="<%# GetStatusPicture(Container.DataItem) %>"
                                     CommandName="StatusClick"
                                     CommandArgument="<%# Eval("ProductID") %>"
                      /></ItemTemplate>
                </asp:TemplateField>
                <asp:BoundField DataField="ProductID" 
                                HeaderText="ID" 
                                InsertVisible="False" 
                                ReadOnly="True"
                                SortExpression="ProductID" />
                <asp:BoundField DataField="ProductName" 
                                HeaderText="Product" 
                                SortExpression="ProductName" />
                <asp:BoundField DataField="UnitPrice" 
                                DataFormatString="{0:C}" 
                                HeaderText="Price"
                                SortExpression="UnitPrice" />
                <asp:BoundField DataField="UnitsInStock" 
                                HeaderText="UnitsInStock" 
                                SortExpression="Units In Stock" />
            </Columns>
        </asp:GridView>
        <br />
        <asp:Label ID="lblInfo" runat="server" Font-Names="Verdana" Font-Size="Small"></asp:Label>
    
    </div>
    </form>
</body>
</html>
File: Default.aspx.cs
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class GridViewTemplates2 : System.Web.UI.Page
{
  protected string GetStatusPicture(object dataItem)
  {
    int units = Int32.Parse(DataBinder.Eval(dataItem, "UnitsInStock").ToString());
    if (units == 0)
    {
      return "0.gif";
    }
    else if (units > 50)
    {
      return "50.gif";
    }
    else
    {
      return "blank.gif";
    }
  }
  protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
  {
    if (e.rumandName == "StatusClick")
      lblInfo.Text = "You clicked product #" + e.rumandArgument;
  }

}
File: Web.config
<?xml version="1.0"?>
<configuration xmlns="http://schemas.microsoft.ru/.NetConfiguration/v2.0">
  <appSettings/>
      <connectionStrings>
        <add name="Northwind" connectionString="Data Source=localhost;Initial Catalog=Northwind;Integrated Security=SSPI"/>
      </connectionStrings>
</configuration>



Master-Detail GridView in Single Page

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="MasterDetailsSinglePage" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:GridView id="gridMaster" 
                  runat="server" 
                  GridLines="None" 
          AutoGenerateColumns="False" 
          DataKeyNames="CategoryID" 
          DataSourceID="sourceCategories" 
          OnRowDataBound="gridMaster_RowDataBound">
        <AlternatingRowStyle BackColor="PaleGoldenrod"></AlternatingRowStyle>
        <HeaderStyle Font-Bold="True" BackColor="Tan"></HeaderStyle>
        <FooterStyle BackColor="Tan"></FooterStyle>
        <Columns>
          <asp:TemplateField HeaderText="Category">
            <ItemStyle  VerticalAlign="Top" Width="20%"></ItemStyle>
            <ItemTemplate>
              <br><b><%# Eval("CategoryName") %></b><br>
              <br><%# Eval("Description" ) %><br>
            </ItemTemplate>
          </asp:TemplateField>
          <asp:TemplateField HeaderText="Products">
            <ItemStyle VerticalAlign="Top"></ItemStyle>
            <ItemTemplate>
              <asp:GridView id="DataGrid2" 
                            runat="server" 
                            AutoGenerateColumns="False"
                          BorderStyle="None">
                    <RowStyle ForeColor="#330099" BackColor="White"></RowStyle>
                <HeaderStyle Font-Bold="True" ForeColor="#FFFFCC" BackColor="#990000"></HeaderStyle>
                <Columns>
                  <asp:BoundField DataField="ProductName" HeaderText="Product Name">
                  <ItemStyle Width="250px" />
                  </asp:BoundField>
                  <asp:BoundField DataField="UnitPrice" HeaderText="Unit Price" DataFormatString="{0:C}" />
                </Columns>    
              </asp:GridView>
            </ItemTemplate>
          </asp:TemplateField>
        </Columns>
        <PagerStyle HorizontalAlign="Center" ForeColor="DarkSlateBlue" BackColor="PaleGoldenrod"></PagerStyle>
      </asp:GridView>
        <asp:SqlDataSource ID="sourceCategories" 
                           runat="server" 
                           ConnectionString="<%$ ConnectionStrings:Northwind %>"
                           ProviderName="System.Data.SqlClient" 
                           SelectCommand="SELECT * FROM Categories"/>
        <asp:SqlDataSource ID="sourceProducts" 
                           runat="server" 
                           ConnectionString="<%$ ConnectionStrings:Northwind %>"
                           ProviderName="System.Data.SqlClient" 
                           SelectCommand="SELECT * FROM Products WHERE CategoryID=@CategoryID">
            <SelectParameters>
                <asp:Parameter Name="CategoryID" Type="Int32" />
            </SelectParameters>
        </asp:SqlDataSource>
    </div>
    </form>
</body>
</html>
File: Default.aspx.cs
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class MasterDetailsSinglePage : System.Web.UI.Page
{
  protected void gridMaster_RowDataBound(object sender, GridViewRowEventArgs e)
  {
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
      GridView gridChild = (GridView)e.Row.Cells[1].Controls[1];
      sourceProducts.SelectParameters[0].DefaultValue = gridMaster.DataKeys[e.Row.DataItemIndex].Value.ToString();
      object data = sourceProducts.Select(DataSourceSelectArguments.Empty);
      
      gridChild.DataSource = data;
      gridChild.DataBind();
    }
  }
}



Using Templated Columns with GridView

<%@ Page Language="C#" %>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Using Templated Columns with GridView</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:SqlDataSource ID="productsSource" runat="server"
            ProviderName="System.Data.SqlClient" 
            ConnectionString="<%$ ConnectionStrings:AdventureWorks %>"
            SelectCommand="Select ProductID, Name, ProductNumber, DaysToManufacture, SellStartDate, ReorderPoint from Production.Product">            
        </asp:SqlDataSource>
       <asp:GridView ID="gridProducts" runat="server" DataSourceID="productsSource"
            AutoGenerateColumns="False">              
            <Columns>
                <asp:TemplateField HeaderText="Products">
                    <ItemTemplate>
                            <%# Eval("ProductID") %> -
                            <%# Eval("Name") %>                            
                            Product Number: <%# Eval("ProductNumber") %><br />
                            Days to manufacture:<%# Eval("DaysToManufacture") %> <br />
                            Start Date: <%# Eval("SellStartDate", "{0:MM/dd/yy}") %><br />                                  
                            Reorder Point:<%# Eval("ReorderPoint") %>
                    </ItemTemplate>
                </asp:TemplateField> 
            </Columns>
       </asp:GridView>
    </div>
    </form>
</body>
</html>