
In this post i show you how to bind Server Variables to GridviewGridview1.DataSource = Request.ServerVariables;Gridview1.DataBind();I almost blushed - this was too easy - the only problem was that when running itit didn't work out as expected:just a single column is shown. Turns out that theNameValueCollection enumerator just returns the keys - and you are then supposedto 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""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head runat="server"> <title>Untitled Page</title></head><body> <form id="form1" runat="server"> <div> <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnRowDataBound="GridView1_RowDataBound"> <Columns> <asp:TemplateField> <ItemTemplate> <asp:Label ID="lblName" runat="server"></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:TemplateField> <ItemTemplate> <asp:Label ID="lblValue" runat="server"></asp:Label> </ItemTemplate> </asp:TemplateField> </Columns> </asp:GridView> </div> </form></body></html>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; GridView1.DataBind(); } } 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]; } } }