在GridView中编辑和更新

时间:2014-11-26 09:23:45

标签: c# asp.net gridview edit

我尝试为gridview实现编辑和更新按钮的代码,但它似乎对我不起作用。我根据我的要求添加了我的代码,但它无法正常工作。请参阅参考的gridview代码: -

 <asp:GridView ID="grdCSRPageData" runat="server" Width="100%" border="1" Style="border: 1px solid #E5E5E5;" CellPadding="3" AutoGenerateColumns="False" OnDataBound="grdCSRPageData_DataBound" AllowPaging="true" CssClass="hoverTable" OnPageIndexChanging="grdCSRPageData_PageIndexChanging" DataKeyNames="Id" OnRowDeleting="grdCSRPageData_RowDeleting" PageSize="4" ShowFooter="true" OnRowUpdating="grdCSRPageData_RowUpdating" OnRowEditing="grdCSRPageData_RowEditing" OnRowCancelingEdit="grdCSRPageData_RowCancelingEdit">
                <AlternatingRowStyle BackColor="#CCCCCC" />
                <Columns>
                    <asp:BoundField DataField="page_title" HeaderText="Page Title" ItemStyle-Width="30" />
                    <asp:BoundField DataField="page_description" HeaderText="Page Description" ItemStyle-Width="30" />
                    <asp:BoundField DataField="meta_title" HeaderText="Meta Title" ItemStyle-Width="30" />
                    <asp:BoundField DataField="meta_keywords" HeaderText="Meta Keywords" ItemStyle-Width="30" />
                    <asp:BoundField DataField="meta_description" HeaderText="Meta Description" ItemStyle-Width="30" />
                    <asp:BoundField DataField="Active" HeaderText="Active" ItemStyle-Width="30" />
                    <asp:TemplateField HeaderText="Action" HeaderStyle-Width="15%">
                        <EditItemTemplate>
                            <asp:LinkButton ID="lbtnUpdate" runat="server" CommandName="Update" Text="Update" />
                            <asp:LinkButton ID="lbtnCancel" runat="server" CommandName="Cancel" Text="Cancel" />
                        </EditItemTemplate>
                        <ItemTemplate>
                            <asp:ImageButton ID="btnEdit" runat="server" ImageUrl="~/images/edit.png" Width="15" Height="15" CommandName="Edit"  />
                            <asp:ImageButton ID="btnDelete" AlternateText="Delete" ImageUrl="~/images/delete.png" runat="server" Width="15" Height="15" CommandName="Delete" CommandArgument='<%# Eval("Id") %>' CausesValidation="false" OnClientClick="return confirm('Are you sure you want to delete this record?')" />
                        </ItemTemplate>
                    </asp:TemplateField>
                </Columns>

另请参阅每个编辑/更新事件背后的代码。

 protected void grdCSRPageData_RowEditing(object sender, GridViewEditEventArgs e)
    {
        grdCSRPageData.EditIndex = e.NewEditIndex;
        grdCSRPageData.DataBind();
    }
    protected void grdCSRPageData_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        bool IsUpdated = false;
        int Id = Convert.ToInt32(grdCSRPageData.DataKeys[e.RowIndex].Value.ToString());
        TextBox PageTitle = (TextBox)grdCSRPageData.Rows[e.RowIndex].FindControl("txtPageTitle");
        TextBox PageDesc = (TextBox)grdCSRPageData.Rows[e.RowIndex].FindControl("txtPagedesc");
        TextBox MetaTitle = (TextBox)grdCSRPageData.Rows[e.RowIndex].FindControl("txtmetatitle");
        TextBox Metakeywords = (TextBox)grdCSRPageData.Rows[e.RowIndex].FindControl("txtMetakeywords");
        TextBox Metadesc = (TextBox)grdCSRPageData.Rows[e.RowIndex].FindControl("txtMetadesc");
        DropDownList ddlActive = (DropDownList)grdCSRPageData.Rows[e.RowIndex].FindControl("ddlActiveInactive");

        using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultCSRConnection"].ConnectionString))
        {
            using (SqlCommand cmd = new SqlCommand())
            {   
                cmd.CommandText = "UPDATE tbl_Pages SET page_title=@page_title,page_description=@page_description,meta_title=@meta_title,meta_keywords=@meta_keywords,meta_description=@meta_description,Active=@Active  WHERE Id=@Id";
                cmd.Parameters.AddWithValue("@Id", Id);
                cmd.Parameters.AddWithValue("@page_title", txtPageTitle.Text);
                cmd.Parameters.AddWithValue("@page_description", txtPagedesc.Text);
                cmd.Parameters.AddWithValue("@meta_title", txtmetatitle.Text);
                cmd.Parameters.AddWithValue("@meta_keywords", txtMetakeywords.Text);
                cmd.Parameters.AddWithValue("@meta_description", txtMetadesc.Text);
                cmd.Parameters.AddWithValue("@Active", Convert.ToBoolean(ddlActiveInactive.SelectedValue));
                cmd.Connection = conn;
                conn.Open();
                IsUpdated = cmd.ExecuteNonQuery() > 0;
                conn.Close();
            }
        }
        if (IsUpdated)
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('page updated sucessfully');window.location ='csrpage.aspx';", true);
        }
        else
        {
            //Error Message
        }
        grdCSRPageData.EditIndex = -1;
        grdCSRPageData.DataBind();
    }
    protected void grdCSRPageData_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        grdCSRPageData.EditIndex = -1;
        grdCSRPageData.DataBind();
    }

请帮忙。

1 个答案:

答案 0 :(得分:0)

使用'CommandField'获取编辑解决方案: - 请参阅GridView HTML

<asp:GridView ID="grdCSRPageData" runat="server" Width="100%" border="1" Style="border: 1px solid #E5E5E5;" CellPadding="3" AutoGenerateColumns="False" OnDataBound="grdCSRPageData_DataBound" AllowPaging="true" CssClass="hoverTable" OnPageIndexChanging="grdCSRPageData_PageIndexChanging" DataKeyNames="Id" OnRowDeleting="grdCSRPageData_RowDeleting" PageSize="5" ShowFooter="true" OnRowEditing="grdCSRPageData_RowEditing" OnRowUpdating="grdCSRPageData_RowUpdating" OnRowCancelingEdit="grdCSRPageData_RowCancelingEdit">
                <AlternatingRowStyle BackColor="#CCCCCC" />
                <Columns>
                    <asp:BoundField DataField="page_title" HeaderText="Page Title" ItemStyle-Width="30" ControlStyle-CssClass="k-grid td" />
                    <asp:BoundField DataField="page_description" HeaderText="Page Description" ItemStyle-Width="30" ControlStyle-CssClass="k-grid td" />
                    <asp:BoundField DataField="meta_title" HeaderText="Meta Title" ItemStyle-Width="30" ControlStyle-CssClass="k-grid td" />
                    <asp:BoundField DataField="meta_keywords" HeaderText="Meta Keywords" ItemStyle-Width="30" ControlStyle-CssClass="k-grid td" />
                    <asp:BoundField DataField="meta_description" HeaderText="Meta Description" ItemStyle-Width="30" ControlStyle-CssClass="k-grid td" />
                    <asp:BoundField DataField="Active" HeaderText="Active" ItemStyle-Width="30" ControlStyle-CssClass="k-grid td" />
                    <asp:TemplateField HeaderText="Action" HeaderStyle-Width="15%">
                        <ItemTemplate>
                            <asp:ImageButton ID="btnDelete" AlternateText="Delete" ImageUrl="~/images/delete.png" runat="server" Width="15" Height="15" CommandName="Delete" CommandArgument='<%# Eval("Id") %>' CausesValidation="false" OnClientClick="return confirm('Are you sure you want to delete this record?')" />
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:CommandField ButtonType="Image" ItemStyle-Width="15" EditImageUrl="~/images/edit.png" ShowEditButton="True" ControlStyle-Width="15" ControlStyle-Height="15" CancelImageUrl="~/images/close.png" UpdateImageUrl="~/images/update.png">
                        <ControlStyle Height="20px" Width="20px"></ControlStyle>
                    </asp:CommandField>
                </Columns>
            </asp:GridView>

另请参阅背后的代码供您参考: -

 protected void grdCSRPageData_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {

        bool IsUpdated = false;
        //getting key value, row id
        int Id = Convert.ToInt32(grdCSRPageData.DataKeys[e.RowIndex].Value.ToString());

        //get all the row field detail here by replacing id's in FindControl("")..

        GridViewRow row = grdCSRPageData.Rows[e.RowIndex];
        TextBox PageTitle = ((TextBox)(row.Cells[0].Controls[0]));
        TextBox PageDesc = ((TextBox)(row.Cells[1].Controls[0]));
        TextBox MetaTitle = ((TextBox)(row.Cells[2].Controls[0]));
        TextBox Metakeywords = ((TextBox)(row.Cells[3].Controls[0]));
        TextBox Metadesc = ((TextBox)(row.Cells[4].Controls[0]));
        TextBox ddlActive = ((TextBox)(row.Cells[5].Controls[0]));

        using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultCSRConnection"].ConnectionString))
        {
            SqlCommand cmd = new SqlCommand();

            cmd.CommandText = "UPDATE tbl_Pages SET page_title=@page_title,page_description=@page_description,meta_title=@meta_title,meta_keywords=@meta_keywords,meta_description=@meta_description,Active=@Active  WHERE Id=@Id";

            cmd.Parameters.AddWithValue("@Id", Id);
            cmd.Parameters.AddWithValue("@page_title", PageTitle.Text);
            cmd.Parameters.AddWithValue("@page_description", PageDesc.Text);
            cmd.Parameters.AddWithValue("@meta_title", MetaTitle.Text);
            cmd.Parameters.AddWithValue("@meta_keywords", Metakeywords.Text);
            cmd.Parameters.AddWithValue("@meta_description", Metadesc.Text);
            cmd.Parameters.AddWithValue("@Active", ddlActive.Text == "1" ? true : false);

            cmd.Connection = conn;
            conn.Open();
            IsUpdated = cmd.ExecuteNonQuery() > 0;
            conn.Close();

        }
        if (IsUpdated)
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('page updated sucessfully');window.location ='csrpage.aspx';", true);
            BindGrid();
        }
        else
        {
            //Error while updating details

            grdCSRPageData.EditIndex = -1;
            //bind gridview here..
            grdCSRPageData.DataBind();
        }
    }