Solved

Encrypt and Decrypt GridView Data

Posted on 2010-08-20
18
2,052 Views
Last Modified: 2012-05-10
Hello,

I have the following code below that I need help with. I need to be able to decrypt the data from my database to my GridView control. The decryption does work if I just decrypt to a Label(s) controls but having issues decrypting to GridView control.

HTML Markup:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="retrievedata.aspx.cs" Inherits="retrievedata" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnRowDataBound="GridView1_RowDataBound">
            <Columns>
                <asp:BoundField DataField="admin_name" HeaderText="Name" />
                <asp:BoundField DataField="admin_address" HeaderText="Name" />
            </Columns>
        </asp:GridView>
    </div>
    </form>
</body>
</html>


CODEBEHIND:

using EncryptionUtility.APress.ProAspNet.Utility;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;

public partial class retrievedata : System.Web.UI.Page
{
    private string EncryptionKeyFile;
    protected void Page_Load(object sender, EventArgs e)
    {
        EncryptionKeyFile = Server.MapPath("key.config");
        SymmetricEncryptionUtility.AlgorithmName = "Rijndael";

        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Admissions"].ConnectionString);

        SqlCommand cmd = new SqlCommand();
        cmd.CommandText = "Admissions_RetrieveCollectedInfoValues";
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Connection = conn;

        try
        {
            conn.Open();

            SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);

            GridView1.DataSource = rdr;
            GridView1.DataBind();

        }

        catch
        {
        }

        finally
        {
            conn.Close();
        }
    }

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.DataItem != null)
        {
            DataRowView dr = (DataRowView)e.Row.DataItem;
            byte[] Address = (byte[])dr["admin_address"];

            System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
            e.Row.Cells[1].Text = SymmetricEncryptionUtility.DecryptData(Address, EncryptionKeyFile);

        }
    }

}
0
Comment
Question by:asp_net2
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 12
  • 4
  • 2
18 Comments
 
LVL 20

Expert Comment

by:informaniac
ID: 33484608
R u getting any value in Address variable
0
 
LVL 4

Author Comment

by:asp_net2
ID: 33484689
yes, when I run the following code above I get the following output below in the image that i'm going to attach.


ee.png
0
 
LVL 4

Author Comment

by:asp_net2
ID: 33484994
Hi informaniac,

Just an FYI, the field in the DB that holds the enrypted data is a varbinary field.
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 4

Author Comment

by:asp_net2
ID: 33486012
Hi informaniac,

are you still able to assist or are you busy now?
0
 
LVL 12

Expert Comment

by:CmdoProg2
ID: 33486066
Assist - I do not use SymmetricEncryptionUtility class, but on mine decryption method need to direct type converson.   Also, I use a templatefield with label/textbox controls.
0
 
LVL 4

Author Comment

by:asp_net2
ID: 33486101
can you show me what i'm going wrong then? Or is it different from what I have/use compared to your code?
0
 
LVL 12

Expert Comment

by:CmdoProg2
ID: 33486613
try ...
        e.Row.Cells[1].Text = (string)SymmetricEncryptionUtility.DecryptData(Address, EncryptionKeyFile);

in mine (Converted from VB)
      Label lbl = (Label)e.Row.Cells[1].Controls(1); // you may want to use FindControl
      lbl.Text = (string)clsEncryption.Decrypt(boundValue);

from my experience, the text property in a cell does not work the same as a label/textbox text property.  informaniac may be more helpful on the conversion.
0
 
LVL 4

Author Comment

by:asp_net2
ID: 33487012
I tried using your code below and the same output is displayed as in post 33484689. Also, the code that I posted is in regards to retrieving data to the GridView not to a Label control. However, I tested the decrpyt code by binding the values to Label controls and the data get decrypted fine, I'm just having trouble decrypting within the GridView.
0
 
LVL 20

Expert Comment

by:informaniac
ID: 33488014
Can u just try this if it works?

Put a templatecolumn instead of a boundcolumn and place a label inside the templatecolumn.

And in rowdatabound set the label text to the decrypted data.
0
 
LVL 4

Author Comment

by:asp_net2
ID: 33488131
Ok, I added the following below to my HTML page but not sure what to add to my codebehind. Please be specific since I'm a noob at this.

        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnRowDataBound="GridView1_RowDataBound" Width="400px">
            <Columns>
                <asp:BoundField DataField="admin_name" HeaderText="Name" />
                <asp:TemplateField><asp:Label ID="Label1" runat="server"></asp:Label></asp:TemplateField>
            </Columns>        
        </asp:GridView>



    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.DataItem != null)
        {
            DataRowView rdr = (DataRowView)e.Row.DataItem;

            byte[] Address = (byte[])rdr["admin_address"];
            e.Row.Cells[1].Text = SymmetricEncryptionUtility.DecryptData(Address, EncryptionKeyFile);

        }
    }
0
 
LVL 20

Accepted Solution

by:
informaniac earned 500 total points
ID: 33491296
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
      if(e.Row.RowType == DataControlRowType.DataRow)
      {
        if (e.Row.DataItem != null)
        {
            DataRowView rdr = (DataRowView)e.Row.DataItem;

            byte[] Address = (byte[])rdr["admin_address"];
            Label Label1 = (Label)e.Row.FindControl("Label1");
            Label1.Text =  SymmetricEncryptionUtility.DecryptData(Address, EncryptionKeyFile);


        }
      }
    }
0
 
LVL 20

Expert Comment

by:informaniac
ID: 33491304
Just being inquisite, how does this line help in ur code

 System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
0
 
LVL 4

Author Comment

by:asp_net2
ID: 33500002
I have taken the following line out below that you mention and the effect is still the same.

>> Just being inquisite, how does this line help in ur code
>> System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
0
 
LVL 4

Author Comment

by:asp_net2
ID: 33500013
Hi informaniac,

I tried the code that you posted above and when I run it I get the following error message below.

Server Error in '/Admissions' Application.
--------------------------------------------------------------------------------

Parser Error
Description: An error occurred during the parsing of a resource required to service this request. Please review the following specific parse error details and modify your source file appropriately.

Parser Error Message: Type 'System.Web.UI.WebControls.TemplateField' does not have a public property named 'Label'.

Source Error:


Line 13:             <Columns>
Line 14:                 <asp:BoundField DataField="admin_name" HeaderText="Name" />
Line 15:                 <asp:TemplateField><asp:Label ID="Label1" runat="server"></asp:Label></asp:TemplateField>
Line 16:             </Columns>        
Line 17:         </asp:GridView>
 

Source File: /Admissions/retrievedata.aspx    Line: 15
0
 
LVL 4

Author Comment

by:asp_net2
ID: 33501073
Hi informaniac,

Are you still able to assist? Also, I make changes to the HTML markup which I'm going to post to show you what I have now. When I run the page this time I don't see any error messages but I also don't see the encrypted data either.

HTML MARKUP:

        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
            OnRowDataBound="GridView1_RowDataBound" Width="400px">
            <Columns>
                <asp:BoundField DataField="admin_name" HeaderText="Name" />
               
                <asp:TemplateField>
                <ItemTemplate><asp:Label ID="Label1" runat="server"></asp:Label></ItemTemplate>
                </asp:TemplateField>
               
            </Columns>    
             
        </asp:GridView>


CODEBEHIND:

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            if (e.Row.DataItem != null)
            {
                DataRowView rdr = (DataRowView)e.Row.DataItem;

                byte[] Address = (byte[])rdr["admin_address"];
                Label Label1 = (Label)e.Row.FindControl("Label1");
                Label1.Text = SymmetricEncryptionUtility.DecryptData(Address, EncryptionKeyFile);
            }
        }
    }
0
 
LVL 4

Author Comment

by:asp_net2
ID: 33504125
Hi informaniac,

Are you still able to help?
0
 
LVL 4

Author Comment

by:asp_net2
ID: 33517352
Hello, anyone still able to help?? If not then I plan on grading this post as is which further help by tomorrow morning.
0
 
LVL 4

Author Closing Comment

by:asp_net2
ID: 33524674
closing post because it was never followed up with.
0

Featured Post

Creating Instructional Tutorials  

For Any Use & On Any Platform

Contextual Guidance at the moment of need helps your employees/users adopt software o& achieve even the most complex tasks instantly. Boost knowledge retention, software adoption & employee engagement with easy solution.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

I recently went through the process of creating a Calendar Control of events with the basis of using a database to keep track of the dates that are selectable, one requirement was to have the selected date pop-up in a simple lightbox.  At first this…
Today is the age of broadband.  More and more people are going this route determined to experience the web and it’s multitude of services as quickly and painlessly as possible. Coupled with the move to broadband, people are experiencing the web via …
In this video we outline the Physical Segments view of NetCrunch network monitor. By following this brief how-to video, you will be able to learn how NetCrunch visualizes your network, how granular is the information collected, as well as where to f…
Do you want to know how to make a graph with Microsoft Access? First, create a query with the data for the chart. Then make a blank form and add a chart control. This video also shows how to change what data is displayed on the graph as well as form…

696 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question