How To Bind All Server Variables In GridView using NameValueCollectio

In this post i show you how to bind Server Variables to Gridview
Gridview1.DataSource = Request.ServerVariables;
I almost blushed - this was too easy - the only problem was that when running it
it didn't work out as expected:just a single column is shown. Turns out that the
NameValueCollection enumerator just returns the keys - and you are then supposed
to retrieve the value yourself.

There are more than one solution for this, you could for example create a convert function which converts the Request.ServerVariables to something like a hashtable, but but here's how I did it (not saying one is better than another):

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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
<html xmlns="">
<head runat="server">
<title>Untitled Page</title>
<form id="form1" runat="server">
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"
<asp:Label ID="lblName" runat="server"></asp:Label>
<asp:Label ID="lblValue" runat="server"></asp:Label>

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Specialized;

public partial class ServerVariable : System.Web.UI.Page
protected void Page_Load(object sender, EventArgs e)
if (!IsPostBack)
GridView1.DataSource = Request.ServerVariables;

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
if (e.Row.RowType == DataControlRowType.DataRow)
// By accepting the fact that we only get the key as DataItem from
//the NameValueCollection, then we use the datasource (which is a NameValueCollection)
//to retrieve the value in RowDataBound:

NameValueCollection oColl = GridView1.DataSource as NameValueCollection;
Label lblName = e.Row.FindControl("lblName") as Label;
lblName.Text = e.Row.DataItem.ToString();

Label lblValue = e.Row.FindControl("lblValue") as Label;
lblValue.Text = oColl[lblName.Text];


No comments:

Post a Comment