asp.net夜话之八:数据绑定控件
在asp.net中所有的数据库绑定控件都是从BaseDataBoundControl这个抽象类派生的,这个抽象类定义了几个重要属性和一个重要方法:DataSource属性:指定数据绑定控件的数据来源,显示的时候程序将会从这个数据源中获取数据并显示。DataSourceID属性:指定数据绑定控件的数据源控件的ID, 显示的时候程序将会根据这个ID找到相应的数据源控件,并利用这个数据源控件中指定方法获取数据并显示。DataBind()方法:当指定了数据绑定控件的DataSource属性或者DataSourceID属性之后,再调用DataBind()方法才会显示绑定的数据。并且在使用数据源时,会首先尝试使用DataSourceID属性标识的数据源,如果没有设置DataSourceID时才会用到DataSource属性标识的数据源。也就是说DataSource和DataSourceID两个属性不能同时使用。数据绑定控件的DataSource控件属性必须是一个可以枚举的数据源,如实现了ICollection、IEnumerable或IListSource接口的类的实例。

解决方案 »

  1.   

    用TemplateColumn,按照指定的模板显示列中的各项。这使您可以在列中提供自定义控件。 下面的代码示例演示如何使用 TemplateColumn 类在 DataGrid 控件中创建具有自定义布局的列。<%@ Page Language="C#" AutoEventWireup="True" %>
    <%@ Import Namespace="System.Data" %><html>
       <script runat="server">      DataTable Store = new DataTable();
          DataView StoreView;        void Page_Load(Object sender, EventArgs e) 
          {
             if(Session["StoreData"] == null)
             {
                DataRow dr;
     
                Store = new DataTable();                  Store.Columns.Add(new DataColumn("Tax", typeof(String)));
                Store.Columns.Add(new DataColumn("Item", typeof(String)));
                Store.Columns.Add(new DataColumn("Price", typeof(String)));            Session["StoreData"] = Store;
                
                // Create sample data.
                for (int i = 1; i <= 4; i++) 
                {
                   dr = Store.NewRow();               dr[0] = "0.0%";
                   dr[1] = "Item " + i.ToString();
                   dr[2] = (1.23 * (i + 1)).ToString();
     
                   Store.Rows.Add(dr);
                }                }
             else
                Store = (DataTable)Session["StoreData"];         StoreView = new DataView(Store);
             StoreView.Sort="Item";         if(!IsPostBack)                    
                BindGrid();
                       
          }      void MyDataGrid_Edit(Object sender, DataGridCommandEventArgs e) 
          {
             MyDataGrid.EditItemIndex = e.Item.ItemIndex;
             BindGrid();
          }      void MyDataGrid_Cancel(Object sender, DataGridCommandEventArgs e) 
          {
             MyDataGrid.EditItemIndex = -1;
             BindGrid();
          }      void MyDataGrid_Update(Object sender, DataGridCommandEventArgs e) 
          {
             // Get the text box that contains the price to edit. 
             // For bound columns the edited value is stored in a text box.
             // The text box is the first control in the Controls collection.
             TextBox priceText = (TextBox)e.Item.Cells[3].Controls[0];         // Get the check box that indicates whether to include tax from the 
             // TemplateColumn. Notice that in this case, the check box control is
             // second control in the Controls collection.
             CheckBox taxCheck = (CheckBox)e.Item.Cells[2].Controls[1];         String item = e.Item.Cells[1].Text;
             String price = priceText.Text;
           
             DataRow dr;         // With a database, use an update command.  Since the data source is 
             // an in-memory DataTable, delete the old row and replace it with a new one.         // Remove old entry.
             StoreView.RowFilter = "Item='" + item + "'";
             if (StoreView.Count > 0)
                StoreView.Delete(0);
             StoreView.RowFilter = "";
     
             // Add new entry.
             dr = Store.NewRow();         if (taxCheck.Checked)
                dr[0] = "8.6%";
             else 
                dr[0] = "0.0%";
             dr[1] = item;
             dr[2] = price;
             Store.Rows.Add(dr);         MyDataGrid.EditItemIndex = -1;
             BindGrid();
          }      void BindGrid() 
          {
             MyDataGrid.DataSource = StoreView;
             MyDataGrid.DataBind();
          }   </script><body>   <form runat="server">      <h3>TemplateColumn Example</h3>      <asp:DataGrid id="MyDataGrid" runat="server"
               BorderColor="black"
               CellPadding="2"        
               OnEditCommand="MyDataGrid_Edit"
               OnCancelCommand="MyDataGrid_Cancel"
               OnUpdateCommand="MyDataGrid_Update"
               ShowFooter="True"
               AutoGenerateColumns="false">         <Columns>            <asp:EditCommandColumn
                     EditText="Edit"
                     CancelText="Cancel"
                     UpdateText="Update"
                     ItemStyle-Wrap="false"
                     HeaderText="Edit Controls"/>            <asp:BoundColumn HeaderText="Description" 
                     ReadOnly="true" 
                     DataField="Item"/>            <asp:TemplateColumn>               <HeaderTemplate>
                      <b> Tax </b>
                   </HeaderTemplate>               <ItemTemplate>
                      <asp:Label
                           Text='<%# DataBinder.Eval(Container.DataItem, "Tax") %>'
                           runat="server"/>
                   </ItemTemplate>               <EditItemTemplate>                  <asp:CheckBox
                           Text="Taxable" 
                           runat="server"/>               </EditItemTemplate>               <FooterTemplate>
                      <asp:HyperLink id="HyperLink1"
                           Text="Microsoft"
                           NavigateUrl="http://www.microsoft.com"
                           runat="server"/>
                   </FooterTemplate>            </asp:TemplateColumn>            <asp:BoundColumn HeaderText="Price" 
                     DataField="Price"/>         </Columns>      </asp:DataGrid>   </form></body>
    </html>里面还可以根据当前列或者本行所在的其它的某种逻辑来决定数据显示。
      

  2.   

    最简单的使用模板,其次你可以在cs里面初始化datagrid时动态绑定