Milan
Milan

Reputation: 83

GridView Row editing - change values

I need to change values during edit in GridView. I'm using a method Decrypt(object) from codebehind. It works for Eval(), but not work Bind().

<asp:GridView ID="GridView1" runat="server" 
          DataKeyNames="ID" DataSourceID="entityDataSource1" >
  <Columns>
     <asp:TemplateField>
        <ItemTemplate>
            <asp:Label ID="lblTab1" runat="server" 
                             Text='<%# Decrypt(Eval("Name")) %>' />
        </ItemTemplate>
        <EditItemTemplate>
            <asp:TextBox ID="lblTab1" runat="server" 
                             Text='<%# Decrypt(Bind("Name")) %>' />
         </EditItemTemplate>
     </asp:TemplateField>
  </Columns>
</asp:GridView>

Upvotes: 0

Views: 2795

Answers (2)

Rob
Rob

Reputation: 1492

Eval() and Bind() are quite different creatures - Eval() is just shorthand for DataBinder.Eval() but Bind() is interpreted by the ASP.NET parser and broken into two parts - one for binding data to the control and the other for moving data from the control to your model.

This is described nicely in this old blog post: How ASP.NET databinding deals with Eval and Bind statements

You don't mention what you are binding to; if you are binding to a business object then you could create a getter/setter property for an un-encrypted Name. Alternatively you could provide an implementation of OnRowUpdating, and perform the Decrypt there. (hint: update the NewValues[] member with the decrypted value).

Upvotes: 0

aledpardo
aledpardo

Reputation: 761

When I need to do this, I usually set the TextBox Text property on the code behind on the RowDataBound event. It's like this:

protected void GridView1_RowDataBound( Object sender, System.Web.UI.WebControls.GridViewRowEventArgs e ) {
    if( e.Row.RowType == DataControlRowType.DataRow && e.Row.RowState == DataControlRowState.Edit ) {
        TextBox txt = ( TextBox )e.Row.FindControl( "lblTab1" );
        if( txt != null ) {
            DataRowView drv = ( DataRowView )e.Row.DataItem;
            txt.Text = Decrypt( drv["Name"].ToString() );
        }
    }
}

For this work, your GridView EditIndex property must be set with your actual index being edited.

Upvotes: 1

Related Questions