65.9K
CodeProject 正在变化。 阅读更多。
Home

DataGridDemo

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.62/5 (40投票s)

2002年7月16日

CPOL

7分钟阅读

viewsIcon

573537

downloadIcon

4148

利用 ASP.NET DataGrid 尽享乐趣和收益

引言

ASP.NET DataGrid 控件功能强大且用途广泛。它几乎可以不费吹灰之力地绑定并显示数据集,并且可以轻松扩展该控件以满足项目的需求,我们将在本教程中看到这一点。

自动生成列

使用 DataGrid 最简单的方法是让 .NET 库完成工作。这可以通过将 AutoGenerateColumns 属性设置为 true 并将其绑定到数据源来轻松实现。

DataGrid1.DataSource = sqlCmd.ExecuteReader();
DataGrid1.DataBind();

上面的代码会将从 SqlCommand.ExecuteReader 方法返回的 SqlDataReader 分配给 DataGrid1.DataSource。调用 DataGrid1.DataBind() 将使控件遍历 DataReader 并创建列并根据内容适当填充行。

绑定列

AutoGenerateColumns 方法的一个缺点是数据集中的所有列都将显示。如果需要更多控制,则需要使用绑定列。要访问 DataGrid 属性对话框,请右键单击表单上的 DataGrid 并选择“属性生成器”,或者单击属性浏览器中列集合旁边的省略号按钮。

要添加绑定列,请在“可用列”列表框中选择它,然后单击箭头按钮。在本例中,在“选定列”列表框中选择“名字”列。添加新列时,它将在列表框中显示为“绑定列”。现在可以设置必要的属性以在 DataGrid 中显示该列。如果要在该列的标题中显示名称,请在“标题文本”文本框中输入。这也会更改“选定列”列表框中的名称。在“数据字段”文本框中输入要绑定到此列的数据集中的字段名称。

“数据格式化表达式”文本框用于对显示的数据应用任何格式。例如,如果该字段是数字类型,并且您希望将其显示为货币,则在该字段中输入 {0:c}。可以利用“可见”复选框隐藏您希望填充但不显示的列。可以通过在“选定列”列表框中上下移动列来更改列的顺序。

超链接列

超文本列显然用于在数据列中显示超文本链接。链接的文本可以在“文本”文本框中配置,URL 可以在“URL”文本框中配置。与绑定列一样,“文本字段”文本框用于设置要将此列绑定到的数据集字段。这只会设置超链接的文本,而不会设置 URL。“URL 字段”用于将链接绑定到数据集字段。“URL 格式字符串”用于在必要时格式化超链接。

模板列

为了更具创意地呈现 DataGrid,我们需要使用模板列。任何列都可以通过单击 DataGrid 属性页面上的链接来更改为模板列。如本代码片段所示,默认模板在正常显示时使用标签控件,在编辑模式下使用文本框控件。

<asp:TemplateColumn HeaderText="First Name">
    <ItemTemplate>
        <asp:Label runat="server" 
        Text='<%# DataBinder.Eval(Container, "DataItem.au_fname") %>' />
    </ItemTemplate>
    <EditItemTemplate>
        <asp:TextBox runat="server" 
        Text='<%# DataBinder.Eval(Container, "DataItem.au_fname") %>' />
    </EditItemTemplate>
</asp:TemplateColumn>

这些控件的 Text 属性通过使用 DataBinder.Eval 方法进行设置。此静态方法使用反射在运行时评估第一个参数。在这种情况下,Container 是绑定到 DataGridDataReader 中的 DataRow。第二个参数 DataItem.au_fname 表示 DataRow 中的列。参数也可以写成 Container.DataItem 和 "au_fname",这使得它稍微更清晰。

编辑模式

要将 DataGrid 置于编辑模式,您需要将 EditItemIndex 属性设置为有效的行索引并重新绑定 DataGridDataGrid 将再次呈现,但这次将为指定行使用 EditTemplate

DataGrid1.EditItemIndex = 1;
BindData();

尽管 DataGrid.EditItemIndex 可以随时设置,但最用户友好的方式是创建按钮列。展开“可用列”列表框中的“按钮列”项将显示三个预定义的按钮列。为了我们的目的,添加“编辑”、“更新”、“取消”按钮列。我们将保留属性的默认值,但可以通过编辑相应的文本框来更改每个按钮显示的文本。“按钮类型”组合框用于选择按钮的显示方式,作为超链接或普通按钮。

如这里所示,EditCommandColumn 将被添加到 DataGrid 中。在正常呈现期间,该列将包含一个“编辑”链接按钮;在编辑模式下,该列将同时包含一个“更新”和“取消”链接按钮。

<asp:EditCommandColumn ButtonType="LinkButton" UpdateText="Update" 
     CancelText="Cancel" EditText="Edit"></asp:EditCommandColumn>

由于这些是 CommandButtons,您必须处理生成的事件并提供任何必要的处理。事件可以从 DataGrid 的属性浏览器的“事件”视图中添加。

在 Edit 事件处理程序中,可以使用 Item.DataSetIndex 设置 DataGrid.EditItemIndex。此属性包含生成事件的行在 DataGrid 中的索引。

private void OnEdit(object source, 
                    System.Web.UI.WebControls.DataGridCommandEventArgs e)
{ 
    DataGrid1.EditItemIndex = e.Item.DataSetIndex; BindData(); 
}

要取消编辑,只需将 DataGrid.EditItemIndex 设置为 -1 并重新绑定 DataGrid。在 Update 事件处理程序中,您可以执行任何必要的操作来更新数据源。

更具创意的编辑

如果只想使用文本框进行编辑,上述方法效果很好,但是如果希望用户能够从选定范围输入值,该怎么办?在这种情况下,需要更多一点的创意。在 EditItemTemplate 中,文本框控件可以替换为下拉列表控件。

<asp:dropdownlist DataSource='<%# LoadNames() %>' 
            DataTextField="au_fname" runat="server"></asp:dropdownlist>

如这里所示,DataSource 属性在运行时通过调用 LoadNames 函数设置。

public ICollection LoadNames()
{
    SqlConnection sqlNewConnection = new SqlConnection();
    sqlNewConnection.ConnectionString = sqlConnection1.ConnectionString;

    SqlDataAdapter da = new SqlDataAdapter("SELECT au_fname FROM authors", 
                                           sqlNewConnection);
    DataSet ds = new DataSet();
    da.Fill(ds);
    
    return ds.Tables[0].DefaultView;
}

请注意,必须创建一个新的 SqlConnection 来获取 DropDownListDataSet。这是因为数据绑定仍在 DatGrid 上进行,并且 SqlConnection 对象在此点仍在使用中。DropDownList 控件绑定到 ICollection 派生对象,在这种情况下,它是第一个 DataSet 表的 DefaultView

用户进行更改并单击“更新”链接后,将调用 OnUpdate 方法。在这里可以确定在 dropdownlist 中选择了哪个项目。如本代码所示,使用 DataGridCommandEventArgs.Item 属性的 FindControl 方法将返回 DropDownList。然后可以根据需要获取 SelectedItem 文本或值。

private void OnUpdate(object source, 
                      System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
    // Find the drop down list
    DropDownList DropList = (DropDownList)e.Item.FindControl("dlNames");
    string strTest = DropList.SelectedItem.Text;

    // Process updated data here

    DataGrid1.EditItemIndex = -1;
    BindData();
}

复选框和文本框

在购物车类型的应用程序中,用户将输入数量或选择复选框,您需要以稍微不同的方式处理 DataGrid。在此示例中,将仅使用 ItemTemplate。这里添加了一个 TextBox 供用户输入数量。OnTextChanged 事件必须手动输入,或者您可以先在 DataGrid 外部创建 TextBox 控件,然后将其复制。

<asp:TemplateColumn HeaderText="Qty">
    <ItemTemplate>
        <asp:TextBox id="TextBox1" runat="server" 
                     Columns="3" MaxLength="3" OnTextChanged="OnQtyChanged">
        </asp:TextBox>
    </ItemTemplate>
</asp:TemplateColumn>

OnTextChange 处理程序是必要的,因为当表单提交时,事件处理的顺序。当点击提交按钮时,表单会发布到服务器,并且 DataGrid 会重新绑定,这会替换已输入到 TextBoxes 中的任何值。通过使用 OnTextChanged 事件,您有机会捕获输入的值并将其存储以备后用。如这里所示,DataGridItem 是从 sender 参数中获取的。TextBox 控件是第一个单元格中的第二个控件,单元格中的第一个控件是 Literal Control,所以我们跳过它。在此示例中,Text 属性被转换为 int 并放入 HashTable 中。

复选框或其他控件也可以以类似的方式使用。

protected void OnQtyChanged( object sender, System.EventArgs e)
{
    // Get the DataGrid row from the sender
    DataGridItem Item = (DataGridItem)
               (((System.Web.UI.Control)sender).NamingContainer);
    
    // Get the TextBox control in the first cell
    TextBox txtQty = (TextBox)Item.Cells[0].Controls[1];
    
    // The au_id field is not an int but if it were...
    //int nID = (int)DataGrid1.DataKeys[Item.ItemIndex];
    // For this demo just use the ItemIndex
    int nID = Item.ItemIndex;

    // Now add to the HashTable
    hashQty.Add(nID, int.Parse(txtQty.Text));
}

结论

要有效地涵盖 DataGrid 的所有功能需要一整本书,但希望这能为您提供在项目中开始使用它所需的基础知识。其他感兴趣的领域是模板样式,它可以让您的 DataGrid 拥有独特的外观。

© . All rights reserved.