Posts Tagged ‘gridview’

Encode HyperLink in GridView using Custom Expression Binding

In my C# Web Application, I have a GridView with a TemplatField. Within the TemplateField is a HyperLink control. My goal is to bind this HyperLink control using Custom Expression Binding. I want the NavigateUrl to point to:

Visit.aspx?name=XXX

XXX in the link above is the database column name. My first instinct is to use the Custom Expression Binding method called Eval() to bind this column. An example of the use of this semi-working method below should be included in the <asp:HyperLink> control.

<asp:HyperLink NavigateUrl=’<%# “Visit.aspx?name=” + Eval(“name”) %>’></asp:HyperLink>

I say this semi-works because the evaulted “name” must not contain any special characters like the ampersand (&). Then the next idea is trying to encode the Eval(“name”). This however was not entirely clear. After researching, I found the following solution.

<asp:HyperLink NavigateUrl=’<%# “Visit.aspx?name=” + HttpUtility.UrlEncode(Eval(“name”).ToString()) %>’></asp:HyperLink>

And this is how to properly encode a hyperlink url that is bound using Custom Expression Binding. Though this may not be visible from the browser, the web page source will reveal that the ampersand (&) has been replaced with %26, which is its equivalent.

The last step on the following page my require decoding the encoded url.

A Scrollable GridView with a Fixed Header in C#

We begin with a standard Panel control. With the Panel control, we can control the width, height, and scrollable option. For our code example, we set the height as 200px, the width as 100%, and set the Panel to scroll while showing only the vertical scrollbars. We will give the Panel the id pnlWrapper.

<asp:Panel ID="pnlWrapper" runat="server" Height="200px" Width="300px" ScrollBars="Vertical">
</asp:Panel>

Our next step is to add to pnlWrapper a GridView that we will assign the id gvScrollableExample. In the sample code below, the GridView will appear as only height 200px and width 300px as we have constrained in pnlWrapper. However, given enough bound data, the Header Row of gvScrollableExample will scroll out of view.

<asp:Panel ID="pnlWrapper" runat="server" Height="200px" Width="300px" ScrollBars="Vertical">
<asp:GridView ID="gvScrollableExample" runat="server">
</asp:GridView>
</asp:Panel>

To fix this, we add a bit of CSS to ensure the Header Row will stay in view. In this situation, the Header Row will act as if it were hoovering above the data. For this to work, we will add inline CSS between the html’s head page as shown below:

<head>
  <style type="text/css">
    .gvFixedHeader
    {
      font-weight:bold;
      position:relative;
      background-color:White;
    }
  </style>
</head>

Next, we have to assign the CSS class to the GridView’s HeaderStyle. This can be done via Visual Studio’s GUI, or we can do it in code. Continuing from our example above, the new extended code will look like:

<asp:Panel ID="pnlWrapper" runat="server" Height="200px" Width="300px" ScrollBars="Vertical">
  <asp:GridView ID="gvScrollableExample" runat="server">
    <HeaderStyle CssClass="gvFixedHeader" />
  </asp:GridView>
</asp:Panel>

The GridView is now ready for you to Bind data. This concludes the tutorial on creating a scrollable GridView with a Fixed Header in Visual Studio. Let me know if there are any questions!

Store Hidden GridView Columns in a DataKey

DataKeyName

When binding a DataTable to a GridView, I always map every column in the DataTable to a new column in GridView (whether it be manually or automatic). I would then hide the columns I did not want to display. In this way, I could still access values in the hidden columns on GridView events such as RowDataBound. A common example of this situation is creating a hidden column for the row’s unique database id.

Since then, I have learned usage practices for a DataKey, which is native to the GridView control. In a high level overview of a DataKey, we simply specify the names of a DataTable’s columns (in which we originally wanted to hide in a GridView) in a comma separated list. The values can then be accessed via the GridView.

For a concrete example, let us assume we have the following information retrieved from a database. The column name id is our primary key from the database:

id firstName lastName age gender
1 Victor Chen 23 M
2 John Doe 26 M
3 Jane Smith 19 F
4 Mary Ann 35 F

We only want to display on the GridView a firstName, lastName, and gender. However, during GridView events, we still want access to the id and age. To setup the GridView, it only takes 3 easy steps!

  1. Place a GridView control on your aspx page.
  2. Manually setup visible columns for firstName, lastName, and gender. (A tutorial on this step)
  3. In the GridView properties and find DataKeyNames (There is an image on what this looks like at the top of this tutorial). Insert a comma separated list for that property: id,age

Now, when you compile and run the page, you will see your GridView is populated with 3 columns. Now to access the hidden values id and age only takes an if statement and one line per hidden column! We will access these values on the RowDataBound event:

protected void gvTemplate_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        int rowIndex = e.Row.DataItemIndex;
        int id = Convert.ToInt32(gvTemplate.DataKeys[rowIndex].Values["id"]);
        int age = Convert.ToInt32(gvTemplate.DataKeys[rowIndex].Values["age"]);
    }
}

In our example above, gvTemplate is the name of our GridView. We access the DataKeys property and specifically access the rowIndex of interest. Because we specified two items id and age in the GridView, we can access them by name. You can also access it by index, but using the actual index’s name makes the code more readable. The final step in the line is to convert the object into the variable type of your choice. If you want, you can shorthand the code with:

gvTemplate.DataKeys[rowIndex]["age"]

You will still need to convert the object into the variable type of your choice. In this case, the best choice is to convert an age it into a integer. And there we have it! We have successfully created a GridView without hidden columns, but still accessible hidden values!