For security reasons Microsoft doesn’t allow invisible columns in a GridView to be posted back like it does in the old DataGrid. That makes it impossible to store the ID of the row in an invisible column and then use it for editing etc. Instead they introduced a much more powerful way of doing the same thing.

Say hello to the new properties DataKeyNames and DataKeys. They allow you to store more than one column of the data source in the ViewState and thus giving you a much easier approach than dealing with invisible columns. In this code sample, I’ll show you how to store a single field in the grid an then use it on a postback.

When you data bind the GridView, you have to tell it in a single line of code what columns of the data source should be saved during postback. In this case, it’s the “id” column.

private void DataBindGrid()
{
  grid.DataKeyNames = new string[] { "id" };
  grid.DataSource = GetDataTable();
  grid.DataBind();
}


After the postback you can then loop through the rows and extract the value “id” column.

private void LoopRows()
{
  for (int i = 0; i < grid.Controls[0].Controls.Count - 1; i++)
  {
    string key = grid.DataKeys[i].Value.ToString();
   
DoSomething(key);
  }
}


You can find more info about how to use the DataKeyNames and DataKeys properties here:

Datagrid to GridView Conversion: No Invisible Columns
gridview column w/visible=false no longer contains cell data in beta 2

The easiest way to make a redirection in ASP.NET is using Response.Redirect(url). What it actually does is, that it creates a response with the “302 (Object Moved)” status code and the target destination. It tells the browser that the requested page is temporarily moved to a new location and then the browser makes a request to the new destination.

If the page is permanently moved, then the 302 status code is no longer correct. Search engines also looks at 301 and 302 redirects differently. Here’s a quote from The Internet Digest:

From a search engine perspective, 301 redirects are the only acceptable way to redirect URLs. In the case of moved pages, search engines will index only the new URL, but will transfer link popularity from the old URL to the new one so that search engine rankings are not affected.

There is no natural way of doing a 301 redirect in ASP.NET, so you have to set the HTTP headers manually. I’ve written a small method that illustrates how to do it. All you have to do is to call it from the Page_Load or preferably from Page_Init or in ASP.NET 2.0 Page_PreInit.

protected void Page_PreInit(object sender, EventArgs e)

{

  PermanentRedirect("http://www.newsite.com");

  PermanentRedirect("/newfolder/");

}

 

private void PermanentRedirect(string url)

{

  Response.Clear();

  Response.StatusCode = 301;

  Response.AppendHeader("location", url);

  Response.End();

}