Friday, June 29

Dynamic Menus and Submenus in an ASP.NET


Introduction

Having a menu and sub menus with links is very normal in a Web application. Typically, we create static menu and menu items. But sometimes we need dynamic menus when we do not know what the menu names and links will be called.
In this article, we will see how to create dynamic menu and sub menus in an ASP.NET application.
Mainly in CMS application we require to customary web layout, Menu and Submenu Items. In this article you learn how to dynamically add Menu and Sub Menu Links for our Web Application.

Step 1: Create Database say (Database.mdf)

Add 2 tables to the database - MainMenu and SubMenu. The table design looks like the following:

Menus1.gif

Step 2: add ConnectionString in web.config. as given below.
<connectionStrings>
<
add name="ConnectionString" connectionString="Data Source=.; AttachDbFilename= DynamicallyControlCreationOfMenuSubmenuItems \App_Data\Database.mdf;User ID=**;Password=*****;Pooling=False" providerName=".NET Framework Data Provider for SQL Server"/></connectionStrings>

Step 3: Open Visual Studio 2005/2008->File->New Website
Menus2.gif

Step 4: Open Solution Explorer ->Add New item

Add CreateMenu.aspx 

Menus3.gif

Step 5: Design the page and Place required Controls in it. As you can see from this design, a user can enter a Menu name, content, order and activate it. Same applies to the sub menu except the fact that user will have to select a main menu. 

Menus4.gif

Menus5.gif

Step 6: Add Main Menu Items by double click on submit Button -> Now write the below code.
  protected void btnMainmenu_Click(object sender, EventArgs e)
  {
     int active;
     if(chkMActive.Checked)
    {
        active=1;
    }
        else    {
        active=0;
    }
SqlConnection conn = new SqlConnection(connection);string sql = "INSERT INTO MainMenu(MainMenu, MContent, MenuOrder,  IsActive)VALUES('"+txtMainmenu.Text+"','"+ txtMContent.Text +"',"+Convert.ToInt16 ( ddlMOrder.SelectedItem.Value)+","+ active+")";
        SqlCommand cmd = new SqlCommand(sql, conn);
        conn.Open();
        cmd.CommandType = CommandType.Text;
        cmd.ExecuteNonQuery();
        conn.Close();
        FillddlMainMenu() ;
        Response.Redirect("SuccessMsg.aspx");
    }

Step 7: Adding Submenus Items.
  1. For this we first need to populate dropdown of Main Menu. Below is the code.   protected void Page_Load(object sender, EventArgs e)
        {
         if (!IsPostBack)
            {
                FillddlMainMenu();
            }
    }
    public void FillddlMainMenu()
    {
            SqlConnection conn =new SqlConnection(connection);
            DataSet DS =new DataSet();
            SqlDataAdapter dataadapter =new SqlDataAdapter();
            SqlCommand cmd =new SqlCommand("Select MainMenuId,MainMenu from  MainMenu", conn);
      
           //cmd.CommandType = CommandType.Text;
            dataadapter.SelectCommand = cmd;
            dataadapter.Fill(DS);
            ddlMainMenu.DataSource = DS;
            ddlMainMenu.DataBind();}
     
  2. Double click on submit Button -> Now write the below code.  protected void btnSubmenu_Click(object sender, EventArgs e)
        {
            int active;
            if (chkSActive.Checked)
            {
                active = 1;
            }
            else        {
                active = 0;
            }
            SqlConnection conn =new SqlConnection(connection);
            string sql ="INSERT INTO SubMenu(SubMenu, Content, MenuOrder,ParentId, IsActive)VALUES('" + txtSubmenu.Text +"','" + txtSContent.Text +"'," +Convert.ToInt16(ddlSOrder.SelectedItem.Value) +"," +Convert.ToInt16(ddlMainMenu.SelectedItem.Value) + "," + active +")";
            SqlCommand cmd =new SqlCommand(sql, conn);
            conn.Open();
            cmd.CommandType = CommandType.Text;
            cmd.ExecuteNonQuery();
            conn.Close();
            Response.Redirect("SuccessMsg.aspx");
        }

Step 8: Now to Show Menu Items we need to add another page. Add 2 Data lists for Main Menu(Horizontally) Submenus Items(Vertically).
Menus6.gif

Step 9: Now Write Code for populating Main Menu Items in datalist to show as menuBar.
 protected void Page_Load(object sender, EventArgs e)
 {
 FillMenu();
 }
  public void FillMenu()
 {
  DataSet ds = new DataSet();
  SqlConnection conn = new SqlConnection(connection);
  SqlDataAdapter dataadapter = new SqlDataAdapter();
  SqlCommand cmd = new SqlCommand("Select * from MainMenu ORDER BY  MenuOrder", conn);
 //cmd.CommandType = CommandType.Text;  dataadapter.SelectCommand = cmd;
  dataadapter.Fill(ds);
  return ds;
    dlSubMenu.DataSource = ds1;
    dlSubMenu.DataBind();
  }
Description: Above code will help to show main menu items as the page loads.

Now we need to populate submenus on selected mainmenu link. We will write code on datalist ItemCommand event.

Step 10: datalist ->Properties ->Add ItemCommand Event.
protected void dlMenu_ItemCommand(object source, DataListCommandEventArgs e)
{
        LinkButton lnkLink = e.Item.FindControl("lnkLink"as LinkButton;
        Label lblPageId = e.Item.FindControl("lblpageId"as Label;
        Session["Sublink"] = lblPageId.Text;
        if (lnkLink.Text != null)
{
            Session["Choice"] = "Main";
            DataSet ds1 = new DataSet();
            SqlConnection conn = new SqlConnection(connection);
            SqlDataAdapter dataadapter = new SqlDataAdapter();
            SqlCommand cmd = new SqlCommand("Select * from SubMenu where IsActive=1 and ParentId='" + Convert.ToInt16(lblPageId.Text) + "' ORDER BY MenuOrder", conn);
            dataadapter.SelectCommand = cmd;
            dataadapter.Fill(ds1);
            dlSubMenu.DataSource = ds1;
            dlSubMenu.DataBind();
        }    }
Step 11: Run application (Press F5).

Summary

The Final Layouts Will be as given Below.

Menus7.gif

Menus8.gif

Menus9.gif

Menus10.gif

Summary
In this article, we discussed how to create a Web site with dynamic menus. The menus and related links were stored in a database and the menus were created at run-time by reading values from the database. 



You can Download The Source Code From C#Corner.First you have to be a user of C#corner.Then You can Download it after login there.
Download Files:


Thanks Shibashish Mohanty

Friday, June 22

Join Three Tables Using Sql Query

Here i have used three tables as shown below


























Data of My Table Looks like this:-
















Sql Query as:-

SELECT        FName
FROM            FTable
WHERE        (FID =
                             (SELECT        T2.FID
                               FROM            TTable AS T2 INNER JOIN
                                                         PTable AS T1 ON T2.PID = T1.PID
                               WHERE        (T1.PID = 1)))


Thanks Shibashish mohanty


Different ways to Bind Data in a TextBox From Gridview Cells by Click on Select Button Using Both RowCommand And SelectedIndexChanged Event

Here i  am using two gridview to show you two different  ways to get data from gridview.

Following is my Table Structure which i am going to use for data binding in gridview:-















My Tables with DataType:-











My Table Data:-








Following is my Design View:-










Here is My Source code:-

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Entitydatamodel.aspx.cs" Inherits="Entitydatamodel" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Shibashish Mohanty</title>
</head>
<body>
    <form id="form1" runat="server">
  
    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    <div id="FirstStyle">
    <div>
    <h1>
    Select Data from gridview and Bind it in Textbox Using RowCommand</h1>
    </div>
        <asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="false"
          
            onrowcommand="GridView2_RowCommand">
        <Columns>
        <asp:BoundField DataField="MenuID" HeaderText="MenuID" />
         <asp:BoundField DataField="Text" HeaderText="Text" />
          <asp:BoundField DataField="Description" HeaderText="Description" />

        </Columns>
        <Columns>
        <asp:TemplateField>
        <ItemTemplate>
            <asp:LinkButton ID="LinkButton1" CommandName="shibashish" CommandArgument='<%# Eval("MenuID") %>'  runat="server">Select</asp:LinkButton>
        </ItemTemplate>
         </asp:TemplateField>
        
        </Columns>
        </asp:GridView>
   
    </div>
 <div id="SecondStyle">
    <div>
    <h1>
    Select Data from gridview and Bind it in Textbox Using
        SelectedIndexChanged </h1>
    </div>
        <asp:GridView ID="GridView3" runat="server" AutoGenerateColumns="false"
         AutoGenerateSelectButton="true"
         onselectedindexchanged="GridView3_SelectedIndexChanged" >
        <Columns>
        <asp:BoundField DataField="MenuID" HeaderText="MenuID" />
         <asp:BoundField DataField="Text" HeaderText="Text" />
          <asp:BoundField DataField="Description" HeaderText="Description" />
          <asp:TemplateField>
         </asp:TemplateField>
        </Columns>
       </asp:GridView>
   
    </div>
   
    </form>
</body>
</html>

Here is My Code Behind:-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Diagnostics;

public partial class Entitydatamodel : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            FillBothGrid();
        }
    }
  
    #region First GridView With RowCommand Event

    public void FillBothGrid()
    {
        TestModel.TestEntities obj = new TestModel.TestEntities();
        GridView2.DataSource = from k in obj.Menus select k;
        GridView2.DataBind();
        GridView3.DataSource = from k in obj.Menus select k;
        GridView3.DataBind();
    }
    protected void GridView2_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        //if (e.CommandName == "shibashish")
        //{
        GridViewRow row = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);

        TextBox1.Text = row.Cells[1].Text;

        //}


    }

    #endregion
#region Second GridView With SelectedIndexChanged Event

    protected void GridView3_SelectedIndexChanged(object sender, EventArgs e)
    {
        GridViewRow gvr = GridView3.SelectedRow;
        TextBox1.Text = gvr.Cells[2].Text;
    }
    #endregion

}


After running it will display as;-













If we will click on the second row of second gridview it will display as














Thanks Shibashish Mohanty



Friday, June 8

Dynamically Change Themes and Style Sheet

Here is I am using Three WebPages
Change Css.aspx
ChangeTheme.aspx
Default.aspx


Source Code of Change Css.aspx:-


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Change Css.aspx.cs" Inherits="Change_Css" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
   
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <br />
        <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
   
    </div>
    </form>
</body>
</html>

 Code Behind of Change Css.aspx:-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Change_Css : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        Session["TxtValue"] = TextBox1.Text;
        Response.Redirect("Default.aspx");
    }
}


Source Code of  Default.aspx :-

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">

    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div id="Test" >
   
        <br />
        <br />
        <br />
        <br />
        <br />
        <br />
        <br />
        <br />
        <br />
        <br />
        <br />
        <asp:Button ID="Button1" runat="server" onclick="Button1_Click"
            style="font-weight: 700; color: #FFFFCC; text-align: right; background-color: #00CC00"
            Text="Return" />
        <br />
        <br />
        <br />
        <br />
        <br />
        <br />
        <br />
        <br />
        <br />
        <br />
        <br />
        <br />
        <br />
        <br />
        <br />
        <br />
   
    </div>
    </form>
</body>
</html>


  Code Behind of  Default.aspx :-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    protected override void OnInit(EventArgs e)
    {
        if (Session["TxtValue"] != null)
        {
            Literal link = new Literal();
            if ("1" == Session["TxtValue"].ToString())
            {
                link.Text = "<link href=\"Css/StyleSheet.css\" rel=\"stylesheet\" type=\"text/css\" />";
            }
            else if ("2" == Session["TxtValue"].ToString())
            {
                link.Text = "<link href=\"Css/StyleSheet2.css\" rel=\"stylesheet\" type=\"text/css\" />";
            }
            else if ("3" == Session["TxtValue"].ToString())
            {
                link.Text = "<link href=\"Css/StyleSheet3.css\" rel=\"stylesheet\" type=\"text/css\" />";
            }
            base.Page.Header.Controls.Add(link);


            base.OnInit(e);
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        Response.Redirect("Change Css.aspx");
    }
}

Source Code of   ChangeTheme.aspx  :-

<%@ Page Language="C#" AutoEventWireup="true" Theme="Theme1" CodeFile="ChangeTheme.aspx.cs" Inherits="ChangeTheme" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div id="Test">
   
        <br />
        <br />
        <br />
        <br />
        <br />
        <br />
        <br />
        <br />
        <br />
   
    </div>
    Change Theme:--<asp:DropDownList ID="DropDownList1" runat="server"  AutoPostBack="true"
        onselectedindexchanged="DropDownList1_SelectedIndexChanged">
        <asp:ListItem>Theme1</asp:ListItem>
        <asp:ListItem>Theme2</asp:ListItem>
        <asp:ListItem>Theme3</asp:ListItem>
    </asp:DropDownList>
    </form>
</body>
</html>

 Code Behind of   ChangeTheme.aspx  :-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class ChangeTheme : System.Web.UI.Page
{
    protected void Page_PreInit(object sender, EventArgs e)
    {

        string theme = "Theme1";

        if (Page.Request.Form.Count > 0)
        {

        

            theme = Request["DropDownList1"].ToString();



        }

        Page.Theme = theme;



    }
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {

    }
}


Thanks Shibashish mohanty






ShibashishMnty
shibashish mohanty