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

ASP.NET 2.0 可编辑 GridView

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.66/5 (119投票s)

2008年2月6日

CPOL

2分钟阅读

viewsIcon

1136087

downloadIcon

55560

本文将概述如何完整地使用 ASP.NET GridView,以及如何在 DataGrid 中使用 RowEditing、RowUpdating、RowDeleting、RowCommand、RowDataBound、RowCancelingEdit 和分页。 通过本文,您将清晰地了解 GridView 数据的插入、删除和

EditableGridView

引言

本文将概述如何完整地使用 asp:GridView,以及如何在 DataGrid 中使用 RowEditingRowUpdatingRowDeletingRowCommandRowDataBoundRowCancelingEdit 和分页。 通过本文,您将清晰地了解 GridView 数据的插入、删除和更新操作。

背景

GridView 是 ASP.NET 中一个非常流行的控件,对于网站开发来说,它是一个非常重要的控件。 此控件对于 CRUD 操作尤其重要。

使用代码

在数据库中创建两张表:ContactContactType。 这只是一个例子,说明我们如何在 GridView 中添加、编辑和删除数据。 我还使用了文本框、下拉列表和复选框,我们在添加、删除和更新数据时使用它们。

循序渐进

创建一个 Web 项目,转到 .aspx 页面,例如 Default.aspx,并添加一个 ASP.NET GridView

<asp:GridView ID="grdContact" runat="server" 
 AutoGenerateColumns="False" DataKeyNames="Id, Type" 
 OnRowCancelingEdit="grdContact_RowCancelingEdit" 
 OnRowDataBound="grdContact_RowDataBound" 
 OnRowEditing="grdContact_RowEditing" 
 OnRowUpdating="grdContact_RowUpdating" ShowFooter="True" 
 OnRowCommand="grdContact_RowCommand" 
 OnRowDeleting="grdContact_RowDeleting">

这是一个 GridView,启用了所有必要的属性并调用了事件。

对于 GridView 的每一列,我们需要创建一个 <asp:TemplateField> 字段。 我使用 <EditItemTemplate> 放置编辑控件,使用 <ItemTemplate> 在控件中绑定数据,使用 <FooterTemplate> 插入控件。 这是一个模板字段的例子

<asp:TemplateField HeaderText="Name" HeaderStyle-HorizontalAlign="Left"> 
   <EditItemTemplate> 
    <asp:TextBox ID="txtName" runat="server" Text='<%# Bind("Name") %>'></asp:TextBox> 
   </EditItemTemplate> 
   <FooterTemplate> 
    <asp:TextBox ID="txtNewName" runat="server" ></asp:TextBox> 
   </FooterTemplate> 
   <ItemTemplate> 
    <asp:Label ID="lblName" runat="server" Text='<%# Bind("Name") %>'></asp:Label> 
   </ItemTemplate>
</asp:TemplateField>

Editable_GridView/Editable_GridView2.png

让我们看看 GridView 的代码

  1. 初始化 GridView:为了在 GridView 中填充数据,我编写了一个名为 FillGrid() 的方法,该方法从 DataTable 中获取数据并在网格中显示它。
        public void FillGrid()
        {
            ContactTableAdapter contact = new ContactTableAdapter();
            DataTable contacts = contact.GetData();        
            if (contacts.Rows.Count > 0)
            {
                grdContact.DataSource = contacts;
                grdContact.DataBind();
            }
            else
            {
                contacts.Rows.Add(contacts.NewRow());
                grdContact.DataSource = contacts;
                grdContact.DataBind();
    
                int TotalColumns = grdContact.Rows[0].Cells.Count;
                grdContact.Rows[0].Cells.Clear();
                grdContact.Rows[0].Cells.Add(new TableCell());
                grdContact.Rows[0].Cells[0].ColumnSpan = TotalColumns;
                grdContact.Rows[0].Cells[0].Text = "No Record Found";
            }
        }
  2. 填充动态值:本例中有两个下拉列表控件可用。 其中一个下拉列表动态地从另一张表中加载数据。 在 GridView 控件的 RowDataBound 事件中,插入以下代码
        protected void grdContact_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            ContactTypeTableAdapter contactType = new ContactTypeTableAdapter();
            DataTable contactTypes = contactType.GetData();
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                Label lblType = (Label)e.Row.FindControl("lblType");
                if (lblType != null)
                {
                    int typeId = Convert.ToInt32(lblType.Text);
                    lblType.Text = (string)contactType.GetTypeById(typeId);
                }
                DropDownList cmbType = (DropDownList)e.Row.FindControl("cmbType");
                if (cmbType != null)
                {   
                    cmbType.DataSource = contactTypes;
                    cmbType.DataTextField = "TypeName";
                    cmbType.DataValueField = "Id";
                    cmbType.DataBind();
                    cmbType.SelectedValue = 
                      grdContact.DataKeys[e.Row.RowIndex].Values[1].ToString();
                }
            }
            if (e.Row.RowType == DataControlRowType.Footer)
            {
                DropDownList cmbNewType = (DropDownList)e.Row.FindControl("cmbNewType");
                cmbNewType.DataSource = contactTypes;
                cmbNewType.DataBind();
            }
        }
  3. 插入数据:我用 DataTable 初始化了 GridView 控件,并且还在页脚下拉列表中填充了一些值,cmbNewType。 除了 Id,我为每一列都放置了 FooterTemplate,因为所有字段都可用。 点击“插入”将在您的数据库表中输入数据。
    protected void grdContact_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        ContactTableAdapter contact = new ContactTableAdapter();
        bool flag= false;
        if (e.CommandName.Equals("Insert"))
        {
            TextBox txtNewName = 
              (TextBox)grdContact.FooterRow.FindControl("txtNewName");
            CheckBox chkNewActive = 
              (CheckBox)grdContact.FooterRow.FindControl("chkNewActive");
            DropDownList cmbNewType = 
              (DropDownList)grdContact.FooterRow.FindControl("cmbNewType");
            DropDownList ddlNewSex = 
              (DropDownList)grdContact.FooterRow.FindControl("ddlNewSex");
            if (chkNewActive.Checked) flag = true; else flag = false;
            contact.Insert(txtNewName.Text, ddlNewSex.SelectedValue, 
                           cmbNewType.SelectedValue, flag);
            FillGrid();
        }
    }
  4. 更新数据:在更新数据的情况下,我们做的事情与插入相同。 在插入的情况下,我总是采用页脚行,但在更新的情况下,我采用当前的 RowIndex 或选定的 RowIndex。 首先点击“编辑”,然后调用 RowEditing,然后出现更新和取消选项。
    protected void grdContact_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        ContactTableAdapter contact = new ContactTableAdapter();
        bool flag = false;
        Label lblId = (Label)grdContact.Rows[e.RowIndex].FindControl("lblId");
        TextBox txtName = (TextBox)grdContact.Rows[e.RowIndex].FindControl("txtName");
        CheckBox chkActive = 
          (CheckBox)grdContact.Rows[e.RowIndex].FindControl("chkActive");
        DropDownList cmbType = 
          (DropDownList)grdContact.Rows[e.RowIndex].FindControl("cmbType");
        DropDownList ddlSex = 
          (DropDownList)grdContact.Rows[e.RowIndex].FindControl("ddlSex");
        if (chkActive.Checked) flag = true; else flag = false;
        contact.Update(txtName.Text, ddlSex.SelectedValue, 
                       cmbType.SelectedValue, flag,Convert.ToInt32(lblId.Text));
        grdContact.EditIndex = -1;
        FillGrid();
        
    }
    protected void grdContact_RowEditing(object sender, GridViewEditEventArgs e)
    {
        grdContact.EditIndex = e.NewEditIndex;
        FillGrid();
    }
    protected void grdContact_RowCancelingEdit(object sender, 
                              GridViewCancelEditEventArgs e)
    {
        grdContact.EditIndex = -1;
        FillGrid();
    }
  5. 删除数据:现在,您可能需要删除数据。 GridView 调用 RowDeleting 用于删除事件。
    protected void grdContact_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        ContactTableAdapter contact = new ContactTableAdapter();
        int id = Convert.ToInt32(grdContact.DataKeys[e.RowIndex].Values[0].ToString());
        contact.Delete(id);
        FillGrid();
    }

关注点

那么,现在您有一个可编辑的 DatGrid 吗? 您想使用 CSS 来给您的网格一个出色的外观吗? 只要访问这个链接,获取 GridView CSS

编码愉快 Smile | :)

历史

我正在我的一个项目中处理一个管理面板,并看到我需要为该面板进行许多添加、删除和更新操作。 现在,通过使用可编辑的 GridView,我可以轻松地解决这个问题,而无需大量的编程。 Smile | :)

© . All rights reserved.