invoke methods on the parent page from the user control

All of us  have used User Controls in our applications, and we have reached a point that we need to call a method on parent page from the user control.

In this article I’m going to write about a simple solution for this case.

we cab do this by using Reflection, Notice that the method we need to call on parent page should be declared Public.

Parent Page Code Behind :

public void ShowMessage(string Mymessage)
{
   Response.Write(message);
}

UserControl Code Behind :
In the user control we have a Textbox and a Button. On the click event of the Button I am calling the Parent Page method we discussed above using Reflection and passing the value of the textbox to the method and then the method is invoked and the message is displayed on the screen.

protected void btnSend_Click(object sender, EventArgs e)
{
   this.Page.GetType().InvokeMember("ShowMessage", System.Reflection.BindingFlags.InvokeMethod, null, this.Page, new object[] { txtMessage.Text });
}

There is one negative point about this method is if you rename the public Method on parent page, the code still compiles without any warnings or errors, but it will explode on run time. the reason for this is you are passing the method name as a string.

Populating ASP.NET Menu Control Recursively

In my fist article I will address a very common issue I think most of us have faced at least once, creating a tree-view from a flat list ( a self-joined database table for example ) maybe populating a asp.net menu control by a list of categories is a good example.

First We will create a database table named categories, bellow is a screenshot of the table schema :

we will use parentID column to create a self-joined table, if a category is a top level parent, then the ParentID will be zero, if not we will set the parent categoryID in parentID.

Bellow is the disused table filled with sample data :

Then we will create a very simple class called Category as follows :

 public class Category
        {
            public int CategoryId;
            public string CategoryName;
            public int ParentId;
            public List ChildCategory = new List();
        }

Using Linq to SQL, i have populated a generic list of Category class, I have called this method GetdatafromDb.

public List GetdatafromDb()
        {
            var FlatList = new List();
            var Mydata = new MydataDataContext();
            var dbResult = from categories in Mydata.Categories
                           select categories;
            foreach (var category in dbResult)
            {
                FlatList.Add(new Category() { CategoryId = category.CategoryID, CategoryName = category.CategoryName, ParentId = category.ParentID });
            }
            return FlatList;
        }

We create a method that will return a List of categories with all their subcategories based on data from GetdatafromDb() Method :

        private List ConvertCategoryListToTree(List flatList)
        {
            var rootNodes = new List();
            foreach (var node in flatList)
            {
                //The parent of this node in the flat list (if there is one).
                var parent = flatList.Find(i => i.CategoryId == node.ParentId);
                if (parent == null)
                {
                    //Collect the root nodes to return later...
                    rootNodes.Add(node);
                }
                else
                {
                    //Ignore orphans (should never happen, but just in case)...
                    if (!flatList.Exists(i => i.CategoryId == node.ParentId))
                        continue;

                    //add this node to the child list of its parent.
                    if (parent.ChildCategory == null)
                        parent.ChildCategory = new List();
                    parent.ChildCategory.Add(node);
                }
            }
            return rootNodes;
        }

we are almost done, we have a generic list of categories and their child categories are hanging off their parent, thats great we just need one other methods to render the asp.net menu Items and their
child items.

 private void BuildChildMenus(List Categorys, MenuItemCollection Items)
        {
            foreach (Category childCategory in Categorys)
            {
                MenuItem menuItem = new MenuItem(childCategory.CategoryName);
                menuItem.NavigateUrl = ResolveUrl("~/category.aspx?ID=") + childCategory.CategoryId;
                Items.Add(menuItem);

                if (childCategory.ChildCategory == null)
                    continue;

                BuildChildMenus(childCategory.ChildCategory, menuItem.ChildItems);
            }
        }

one last thing remaining is adding a asp,net menu control to your page, and add the following line to your Page_Load Method in code behind:

 BuildChildMenus(ConvertCategoryListToTree(GetdatafromDb()), MyMenu.Items);

in the codeine above ‘MyMenu’ is ID of my asp.net Menu Control.

I hope this article helped you save time on a common question most of us have faced.

Happy Coding,

Arash

starting ….

Hello every one,

My approach for this Blog is writing technical articles in asp.net scope, some might be technical and others might be obvious things we all know, but it might help some junior developers.

Hoping everybody finds this blog useful, I’ll try to post at least one article per week, but I will update sooner if I find something that worths sharing with other friends.

Arash