locked
Best way to access DataTable defined in User Control to parent page RRS feed

  • Question

  • User1126057398 posted

    What's the best way to access DataTable defined in User Control to parent page? In parent page I had to use this datatable defined in UserControl to create web method. I had defined it like below but it's not working. In UserControl, I had defined ViewState["Activities"], which I am trying to access in parent page. Parent Page Code to access UC:

    [WebMethod]
    public static ArrayList getChartData()
    {
    ArrayList list = new ArrayList();
    DataTable tbAct= GetActivityData();
    if (tbAct != null)
    {
    foreach (DataRow row in tbAct.Rows)
    {
    list.Add(new ListItem(Convert.ToString(row["DURATION_HOUR"]), Convert.ToString(row["MET_ACTIVITY_DESCRIPTION"])));
    }
    }
    return list;
    }

    public static DataTable GetActivityData()
    {
    var pageType = typeof(Page);
    var viewStatePropertyDescriptor = pageType.GetProperty("ViewState", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
    var currentPageViewState = (StateBag)viewStatePropertyDescriptor.GetValue(HttpContext.Current.CurrentHandler);
    return (DataTable)currentPageViewState["Activities"];
    }

    Tuesday, June 25, 2019 4:56 AM

Answers

  • User1126057398 posted

    In Service class, created a method:

    public static DataTable tbActivities;
    public void SetActivitiesDataTable(DataTable tb)
    {
    tbActivities = tb;
    }
    public DataTable GetActivitiesDataTable()
    {
    return tbActivities;
    }

    In UserControl, called 'SetActivitiesDataTable' method to set DataTable and in parent page used 'GetActivitiesDataTable' method to get datatable like below:
    [WebMethod]
    public static List<ActivityChartData> getChartData()
    {
    List<ActivityChartData> listChartData = new List<ActivityChartData>();
    DataTable tbAct = new DietService().GetActivitiesDataTable();
    if (tbAct != null)
    {
    foreach (DataRow row in tbAct.Rows)
    {
    ActivityChartData ac = new ActivityChartData();
    ac.Activity= Convert.ToString(row["MET_ACTIVITY_DESCRIPTION"]);
    ac.HoursSpent = Convert.ToDecimal(row["DURATION_HOUR"]);

    listChartData.Add(ac);
    }
    }
    return listChartData;
    }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, June 25, 2019 6:51 AM