Question

I have regular asp.net gridview,and i want to enable editmode in each row,and also without editbutton (like excel grid). Edited data i want to save to my database by clicking "Post" button outside the grid(one button for whole grid). How can i reach it?

Was it helpful?

Solution

To achieve this, you are going to have to use ItemTemplates for each column with textboxes in them as the control..

ASP

<asp:TemplateField HeaderText="Heading Title" SortExpression="Heading Title">
                    <ItemTemplate>
                        <asp:TextBox ID="tbTextbox" runat="server" Width="65px" Text='<%# Bind("ColumnNameYouWantToView") %>'></asp:TextBox>                              
                    </ItemTemplate>
 </asp:TemplateField>

After this is set up properly, you will want the post button. You can either put it in the grid or outside the grid. I use both, but here is the one inside the grid as a footer.

ASP

<asp:TemplateField>
        <ItemTemplate>
             <asp:Button ID="btnView" runat="server" Text="View" OnClick="btnView_Click" Width="40px" />
        </ItemTemplate>
        <FooterTemplate>
             <asp:Button ValidationGroup="UPDATE" ID="btnUpdate" OnClick="btnUpdate_Click" runat="server" Text="Update" Width="50px"></asp:Button>
        </FooterTemplate>
        <FooterStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="50px" />
 </asp:TemplateField>

So far, what I have found that works best is using a foreach statement in your button click. The biggest flaw with this idea is that it will update every single row. It works, but if you only change a single row at a time, it will update all of them. I have my pager set to 10, so 10 rows are always updated (unless you are just searching for a single record and update it, the only that single record is updated).

Code Behind C#

protected void btnUpdate_Click(object sender, EventArgs e)
        {
            SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["databaseConnection"].ConnectionString);
            conn.Open();

            //finds the controls within the gridview and updates them
            foreach (GridViewRow gvr in gvGridViewName.Rows)
            {
                string ID = (gvr.FindControl("lblId") as Label).Text.Trim();//finds the control in the gridview
                string anotherControl = ((TextBox)gvr.FindControl("tbTextBox")).Text.Trim();//finds the textbox in the gridview

                 //Your update or insert statements


         }

This is how I do it. You can also look into Real World Grids but I haven't had much luck with this as I would always get an error if a textbox was empty. This however, is suppose to be "smart" enough to just update the rows that have been changed, but again, I didn't have much luck of doing it this way. Hope this helps!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top