Multiple DataKeys Null Conditional

written by Ryan Olshan on Tuesday, December 06 2005

Lets say you have multiple DataKeys assigned to the DataKeyNames property of the GridView control where only one DataKey will have a value and the rest will be null. Based on the non-null value, you want to trigger a conditional. I've discovered an easy to accomplish this is using Reflection and a GridView event. In this example, the value of my DataKeys are all of type integer.

VB.NET
Private Sub GridView_Created(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
   
If e.Row.RowType = DataControlRowType.DataRow Then
       
Dim nKeyVal As Integer

       
If gridView.DataKeys(e.Row.RowIndex).Values("KeyName1").GetType() == Type.GetType("System.Int32") Then
            nKeyVal = 
gridView.DataKeys(e.Row.RowIndex).Values("KeyName1")

            ' Do something

        End If

        If gridView.DataKeys(e.Row.RowIndex).Values("KeyName2").GetType() == Type.GetType("System.Int32") Then
            nKeyVal = 
gridView.DataKeys(e.Row.RowIndex).Values("KeyName2")

           
' Do something
        End If

        If gridView.DataKeys(e.Row.RowIndex).Values("KeyName3").GetType() == Type.GetType("System.Int32") Then
            nKeyVal = 
gridView.DataKeys(e.Row.RowIndex).Values("KeyName3")

            ' Do something
       
End If
    End If
End Sub

C#
private void GridView_Created(object sender, GridViewRowEventArgs e)
{
   
if (e.Row.RowType == DataControlRowType.DataRow)
    {
       
int nKeyVal;

       
if (gridView.DataKeys[e.Row.RowIndex].Values["KeyName1"].GetType() == Type.GetType("System.Int32"))
        {
            nKeyVal = (
int)gridView.DataKeys[e.Row.RowIndex].Values["KeyName1"];

           
// Do something
        }

        if (gridView.DataKeys[e.Row.RowIndex].Values["KeyName2"].GetType() == Type.GetType("System.Int32"))
        {
            nKeyVal = (
int)gridView.DataKeys[e.Row.RowIndex].Values["KeyName2"];

           
// Do something
        }

        if (gridView.DataKeys[e.Row.RowIndex].Values["KeyName3"].GetType() == Type.GetType("System.Int32"))
        {
            nKeyVal = (
int)gridView.DataKeys[e.Row.RowIndex].Values["KeyName3"];

            // Do something
        }

    }
}


Note: gridView is the ID of the GridView control.

R
Kick this post on .NET Kicks

Similar Posts

  1. GridView Sorting
  2. VB.NET GridView Sorting/Paging w/o a DataSourceControl DataSource
  3. Getting the content of a GridView cell on edit

Post a comment