gridview edit mode programmatically

I have a basic gridview to which I am binding the data from the code behind from a SQL stored procedure.

<asp:GridView ID="gvCheckResults" runat="server" 
        OnRowDataBound="gvCheckResults_RowDataBound" 
        RowStyle-CssClass="gridViewRow" 
        CssClass="gridView"
        AlternatingRowStyle-CssClass="gridViewAlternatingRow" 
        HeaderStyle-CssClass="gridViewHeader">
    </asp:GridView>

Databind:

gvCheckResults.DataSource = dataContext.GetResults(Name, Address);
gvCheckResults.DataBind();

if (!IsPostBack)
{
    //Add Edit column.
    CommandField cField = new CommandField();
    cField.EditText = "Edit";
    cField.ShowEditButton = true;
    gvCheckResults.Columns.Insert(0, cField);
}

How can I programmatically add Edit button to each result row?
I know how to do it when the datasource object is setup in the aspx page, but never done it programmatically.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Try Like this

<asp:TemplateField HeaderText="Edit>
    <ItemTemplate>
        <asp:LinkButton Id="lnkEdit" runat="server" CommandName="Edit" Text="Edit"/>
    </ItemTemplate>
    <EditItemTemplate>
        <asp:LinkButton Id="lnkEdit" runat="server" CommandName="Update" Text="Update"/>
        <asp:LinkButton Id="LinkButton1" runat="server" CommandName="Cancel" Text="Cancel"/>
    </EditItemTemplate>
</asp:TemplateField>

OnRowEditEvent() set the gridview edit index to e.newrowindex and bind it again like this.

protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
    GridView1.EditIndex = e.NewEditIndex;
    GridView1.DataBind();
}

protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
    //Write code TO UPDATE YOUR DATABESE THEN WRITE BELOW CODE IN LAST
    // To Find Text of TextBox to get updated value....you get it in string like this.
    //string strName = ((TextBox)grdview1.Rows[e.RowIndex].Cells[YourColumnIndexInWhichTexBoxAppear].Controls[0]).Text;
    GridView1.EditIndex = -1;
    GridView1.DataBind();
}

protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
    GridView1.EditIndex = -1;
    GridView1.DataBind();
}


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x