2012年10月25日 星期四

資料繫結控制項(Simple)

簡單的資料繫結控制項包含: DropDownListListBoxCheckBoxListRadioButtonListBulletedList

Introducing Data-Bound Controls

Introducing

  1. Simple data-bound controls : the controls that inherit from the ListControl
  2. Composite data-bound controls : the controls that inherit from the CompositeDataBoundControl .
  3. Hierarchical data-bound controls : the controls that inherit from the HierarchicalDataBoundControl , such as Menu and TreeView controls.

只要是實作 IEnumerableIListSourceIDataSourceIHierarchicalDatasource 的資料都可以繫結(bind)到資料繫結控制項(data-bound web control)。 資料繫結控制項在執行階段會自動連結到資料來源,並執行 DataBind 方法,將資料載入到控制項上。

Mapping Fields to Templates

A template control is a control that has no default UI. The control simply provides the mechanism for binding to data. The developer supplies the UI in the form of inline templates. The template can contain declarative elements such as HTML and DHTML. The template can also contain ASP.NET data-binding syntax to insert data from the data source.

支援樣板的繫結控制項包括 GridViewDetailsViewFormView 控制項。 這類控制項大都提供以下樣板設計:

  • HeaderTemplate :rendered at the top of the control.
  • FooterTemplate :rendered at the bottom of the control.
  • ItemTemplate :rendered for each row in the data source.
  • AlternatingItemTemplate :alternating item template;.
  • SelectedItemTemplate :render a row that has been selected.
  • SeparatorTemplate :separator template that defines the separation of each item and alternate item.
  • EditItemTemplate :render a row that is in edit mode.

Using the DataBinder Class

The DataBinder class can be used to define code inside your script that controls how a given data source is bound. It provides the static Eval method to parse data-binding expression syntax.

Eval

Eval method uses reflection to perform a lookup of a DataItem property's underlying type by looking at the type metadata that is stored in the type's assembly. After the metadata is retrieved, the Eval method determines how to connect to the given field. This makes writing data binding syntax on your page an easy task. For example, the following shows binding to the Vin property of a Car object:

<%# Eval("Vin") %>

The Eval method also provides format string :

<%# Eval("Price", "{0:C}") %>

Bind

The Eval method is great for one-way (or read-only) data binding. However, it does not support read-write data binding and thus cannot be used for insert and edit scenarios. The Bind method of the DataBinder class, however, can be used for two-way data binding. This makes Bind desirable when editing or inserting records.

<asp:TextBox ID="txtTextBox" RunAt="Server" Text='<%# Bind("FirstName") %>' />

Imagine for example a GridView with a ItemTemplate and EditItemTemplate. If you use Bind or Eval in the ItemTemplate, there will be no difference. If you use Eval in the EditItemTemplate, the value will not be able to be passed to the Update method of the DataSource that the grid is bound to.

Hierarchy of Data-Bound Controls

Simple Data-Bound Controls

這一類型的繫結控制項都是繼承 ListControl 這個抽象的類別。
ListControl 類別包含一個 Items 集合屬性,存放項目集合 (集合由 ListItem 組成)。
每個 ListItem 包含一個顯示用的 Text 屬性,和一個 postback 到主機端的 Value 屬性。

集合中的項目可以透過 Add 方法加入,也可以繫結到資料來源取得。 要繫結到資料來源必須指定 DataSource 屬性,若資料來源包含一個以上的表格,則必須再使用 DataMember 屬性指明繫結的表格。

ListControl 屬性

  • Items :取得清單控制項中項目的集合。
    集合項目由 ListItem 物件組成,該物件包含以下屬性:
  • DataSource :設定繫結的資料來源。
  • DataMember :如果資料來源包含多個不同資料項目清單,必須指明資料清單名稱。
  • SelectedIndex :get or set the index of the selected item
  • SelectedItem :access the selected ListItem
  • SelectedValue :access the value of the selected ListItem
  • AppendDataBoundItems :是否在資料繫結之前清除清單項目。
    • True :keep all items that are currently in the ListControl in addition to appending the items from the data binding.
    • False :clears the Items property prior to binding the data.
  • SelectedIndexChanged :which is raised when the selection in the list control changes between posts to the server.
    set a control's AutoPostback property to True if you intend that it post back to the server

DropDownList

ListBox

The ListBox control is used to display items in a longer list rather than one at a time like the DropDownList. Users can see more data at a given time. The control can also be configured to allow the selection of a single item or multiple items.

<asp:ListBox ID="ListBox1" runat="server" 
    DataSourceID="SqlDataSource1" 
    DataTextField="TerritoryDescription" 
    DataValueField="TerritoryID"
    SelectionMode="Multiple">
</asp:ListBox>
<asp:Button ID="btnListBoxSubmit" runat="server" Text="Submit" onclick="btnListBoxSubmit_Click" />
protected void btnListBoxSubmit_Click(object sender, EventArgs e)
{
    foreach (ListItem i in ListBox1.Items)
    {
        if (i.Selected)
            labMessage.Text = labMessage.Text + "You selected TerritoryID: " + i.Value + "<br />";
    }
}

繫結集合項目範例

<asp:ListBox ID="ListBox4" runat="server"
    SelectionMode="Multiple"
    onselectedindexchanged="ListBox4_SelectedIndexChanged"></asp:ListBox>
            
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
public partial class WebForm2 : System.Web.UI.Page
    {
        public WebForm2()
        {
            this.Init += new EventHandler(BindData);
        }
    
        void BindData(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                ListBox4.DataSource = CultureInfo.GetCultures(CultureTypes.AllCultures);
                ListBox4.DataTextField = "DisplayName";
                ListBox4.DataValueField = "EnglishName";
                ListBox4.DataBind();
            }
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            Label1.Text = "";
            foreach (ListItem item in ListBox4.Items)
            {
                if (item.Selected)
                {
                    Label1.Text += item.Value + item.Text + "<br>";
                }
            }
        }
    }

CheckBoxList

CheckBoxListRadioButtonList 是類似的控制項,一個允許多選,一個只能單選。

要取得 CheckBoxList 選取的項目,可以透過 Items 集合項目。 要取得 RadioButtonList 選取的項目,直接使用 SelectedValue 即可。

  • RepeatColumns :Gets or sets the number of columns to display in the CheckBoxList control。
  • RepeatDirection :Gets or sets a value that indicates whether the control displays vertically or horizontally.
<asp:CheckBoxList ID="CheckBoxList1" runat="server" 
    DataSourceID    = "SqlDataSource1" 
    DataTextField  = "TerritoryDescription" 
    DataValueField  = "TerritoryID" 
    RepeatColumns   = "5"
    RepeatDirection = "Vertical" >
</asp:CheckBoxList>
<asp:Button ID="btnCheckBoxListSubmit" runat="server" Text="Submit" 
onclick="btnCheckBoxListSubmit_Click" />
protected void btnCheckBoxListSubmit_Click(object sender, EventArgs e)
{
    foreach (ListItem item in CheckBoxList1.Items)
    {
        if (item.Selected)
            labMessage.Text = labMessage.Text + "You selected TerritoryID: " + item.Value + "<br />";
    }
}

RadioButtonList

<asp:RadioButtonList ID="RadioButtonList1" runat="server" 
    DataSourceID="SqlDataSource1" 
    DataTextField="TerritoryDescription" 
    DataValueField="TerritoryID" 
    RepeatColumns="5"
    RepeatDirection="Vertical"
    >
</asp:RadioButtonList>
<asp:Button ID="btnRadioButtonListSubmit" runat="server" Text="Submit" 
onclick="btnRadioButtonListSubmit_Click" />
protected void btnRadioButtonListSubmit_Click(object sender, EventArgs e)
{
    labMessage.Text = RadioButtonList1.SelectedValue;
}

BulletedList

The BulletedList control displays an unordered or ordered list of items that renders as HTML ul or ol elements, respectively. This control renders as either bullets or numbers based on the BulletStyle property.

  • BulletStyle :設定項目符號樣式 { Numbered | LowerAlpha | Circle | Disc | ... }
  • DisplayMode :設定顯示模式 {Text | HyperLink | LinkButton}
<asp:BulletedList runat="server" ID="BulletedList1"
    DataSourceID="SqlDataSource1"
    DataTextField="TerritoryDescription"
    DataValueField="TerritoryID" 
    BulletStyle="Circle"
    DisplayMode = "Text" >
</asp:BulletedList>

沒有留言:

張貼留言