samedi 1 janvier 2011

Créer un menu dynamique en asp.net c#

Table Sql:
Structure de la classe Menu


Méthodes de la classe Menu: 

   public static DataTable GetParentMenus( )
     {
            SqlConnection con =new SqlConnection("Data Source=myServerAddress;Initial Catalog=myDataBase;Integrated Security=SSPI;");
            SqlCommand cmd = new SqlCommand("Select m.* from menu m  where m.oidmenuparent is NULL  order by ordre", con);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            da.Fill(dt);
            return dt;
        }
 public static DataTable GetChildMenus(int oidMenuParent)
   {
            Connexion c=new Connexion ();
            SqlConnection con =c.Connection ;
            SqlCommand cmd = new SqlCommand("Select m.* from menu m where m.oidmenuparent =" + oidMenuParent + "  order by ordre", con);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            da.Fill(dt);
            return dt;
 }
Chargement des menus parent:

public MenuItem [] ChargerMenu()
{
   DataTable dtmenu;

      Menus m = new Menus();
   dtmenu = m.GetParentMenus();

   foreach (DataRow r in dtmenu.Rows)
    {
      MenuItem mi=new MenuItem(r["Description"].ToString(), r["oidmenu"].ToString(), null["lien"].ToString());
       menu.Items.Add(mi);
       AddChildMenuItems(mi);

     }
  menu.Items.CopyTo(listemenu, 0);
MenuItem[] listemenu = new MenuItem[menu.Items.Count];
  return listemenu;
}

Chargement des menus enfant:

private void AddChildMenuItems(MenuItem parent)
{
  // Get ID item parents
    int ID = int.Parse(parent.Value.ToString());
  DataTable dtmenuEnfant;
    Menus m = new Menus();
  dtmenuEnfant = m.GetChildMenus(ID);
  if (dtmenuEnfant.Rows.Count > 0)
    {
    foreach (DataRow r in dtmenuEnfant.Rows)
       MenuItem mi = new MenuItem(r["Description"].ToString(), r["oidmenu"].ToString(), null, r["lien"].ToString());
      parent.ChildItems.Add(mi);
      AddChildMenuItems(mi);

        }
}

 
Création des menus:

MenuItem[] m = ChargerMenu();
for (int i = 0; i < m.Count(); i++)
{
// Ajout des menus crées à la MenuStrip principale
// MenuPrincipale est MenuStrip
MenuPrincipale.Items.Add(m.ElementAt(i));
}