Search code examples
asp.netformsdatalistdatakey

How can i access Page.FormViewDetails.DataKey?


I need to get the selected item from DataList in ASPNET in a general logging procedure not knowing the control name or datakey name (can be different from page to page). The only place I can find this data seems to in Page.FormViewDetails.DataKey?

I tried the following:

System.Web.UI.Page page = System.Web.HttpContext.Current.Handler as System.Web.UI.Page;
var _barVariable = typeof(System.Web.UI.Page).GetField("FormViewDetails", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance).GetValue(page);

Bit this gives an object reference not set exception, I can see the content of Page.FormViewDetails in watch and VS debugger: VS debug

Why Am I getting null reference exception? Is there an easier way to access this info?


Solution

  • Found the answer:

    System.Reflection.PropertyInfo strProperty = page.GetType().GetProperty("FormViewDetails", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
    System.Reflection.MethodInfo strGetter = strProperty.GetGetMethod(nonPublic: true);
    
    FormView val = (FormView)strGetter.Invoke(page, null);