I want to decrypt this field o" /> I want to decrypt this field o" /> I want to decrypt this field o"/>

How to change the cell value of a GridView cell WHILE editing?

299 Views Asked by At

I have a GridView with a BoundField:

<asp:BoundField HeaderText="Secret" DataField="encrypted" DataFormatString="***"/>

I want to decrypt this field only when the user edits the row. The logical place to do this seems in RowDataBound(). I tried to use e.Rows.Cells, but that is empty when editing (and would otherwise be '***').

I can get the underlying value using DataRowView, but I can't figure out how to get the decrypted data in the TextBox when editing.

protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        if (e.Row.RowState.HasFlag(DataControlRowState.Edit))
        {
            // When in Normal state, e.Row.Cells[0].Text is '***'
            // When in Edit state, e.Row.Cells[0].Text is empty.
            string cellValue = e.Row.Cells[0].Text; // Always empty

            // Get the encrypted field
            DataRowView rowView = (DataRowView)e.Row.DataItem;
            string decrypted = Decrypt(rowView["encrypted"].ToString());

            // This doesn't work - how to get this value in the edit box?
            e.Row.Cells[0].Text = decrypted;
        }
    }
}

It looks I have to get access to the editing control that is displayed, but how?

1

There are 1 best solutions below

0
Geoduck On

Using a BoundField, there isn't a well documented way to find the edit control. You probably could find it in as the first control in the Cell, but to future proof your solution, I suggest using a templatefield:

<asp:TemplateField  HeaderText = "Secret">

    <ItemTemplate>
        *****
    </ItemTemplate>
    <EditItemTemplate>
        <asp:TextBox ID="txtSecret" runat="server"

            Text='<%# Decrypt(Eval("encrypted").ToString()) %>'></asp:TextBox>

    </EditItemTemplate> 
</asp:TemplateField>

Your Decrypt method must be exposed on the class. Don't really even need the OnRowDataBound