Wednesday, 6 November 2013

Removing White spaces whithin the string

Sometimes we come across situation where we need to remove the whitespace whithin the string.
So here is the simple code for the same.

Step 1: Markup of the page

<asp:TextBox ID="txtAddress" runat="server" TextMode="MultiLine" Columns="20"
            Width="300px" style="height: 300px"></asp:TextBox>
        <br />
        <asp:Button ID="btnCheckAddress" runat="server" Text="Validate Space"
            onclick="btnCheckAddress_Click" />



Step 2: Code

protected void btnCheckAddress_Click(object sender, EventArgs e)
    {
        txtAddress.Text= txtAddress.Text.Trim();//To clear leading and trailing space

        // Following loop is to remove the whitespace within the string
        while (txtAddress.Text.Contains("  "))/Here Contains method check for 2 continues space
        {
            txtAddress.Text = txtAddress.Text.Replace("  ", " ");//Here Replace method will replace 2 continues space with single space
        }
    }


Output:




Monday, 14 October 2013

Google Like Search Box with Suggestion

Here are some tips to generate Google Like Search box with Suggestions.

Step 1: Create a page which will be called on TextChange event of theSearch Text Box and write the code as follows:

using System.Data.SqlClient;
using System.Text; 


string clientName;
    protected void Page_Load(object sender, EventArgs e)
    {
      clientName = Request["search"].ToString();
      Getresult();
       
    }


private void Getresult()
    {
        DataTable dt = new DataTable();      
         SqlConnection con = new SqlConnection();
         con.ConnectionString = "data source=yourServer;initial catalog=yourdatabaseIntegrated security=true;";        
        SqlCommand cmd=new SqlCommand();
        cmd.Connection=con;
        cmd.CommandText = "select studName from tbl_stud1 where studName like @nm";
        cmd.CommandType = CommandType.Text;
        cmd.Parameters.AddWithValue("@nm", clientName + "%");
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        da.Fill(dt);
        StringBuilder sb = new StringBuilder();
      
        if (dt.Rows.Count > 0)
        {
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                sb.Append(dt.Rows[i].ItemArray[0].ToString()  + "~");   //Create Con
            }
        }
           Response.Write(sb.ToString());  
    }


Step 2: Now create the markup of main search page as follows:

<script language="JavaScript" type="text/javascript" src="SearchSuggest.js"></script>
    <style type="text/css" media="screen">   
       body
       {
        font: 11px arial;
       }
       .suggest_link
       {
       background-color: #FFFFFF;
       padding: 2px 6px 2px 6px;
       }   
       .suggest_link_over
       {
       background-color: #3366CC;
       padding: 2px 6px 2px 6px;   

       color: #FFFFFF;
       }   
       #search_suggest
       {
       position: absolute;
       background-color: #FFFFFF;
       text-align: left;
       border: 1px solid #000000;           
       }
    </style>


<table>
    <tr>
    <td style="font: 20px arial" >
    Welcome to Demo of Google like Search Suggest Text Box
    </td>
    </tr>
    </table>
   
   <input type="text" id="txtSearch" name="txtSearch" alt="Search Criteria"       onkeyup="searchSuggest(event);" autocomplete="off" style="width: 544px" />&nbsp;
    <div id="search_suggest" style="z-index: 2; visibility: hidden;position: absolute;left: 11px; width: 548px; top: 70px"></div>
    <input type="submit" id="cmdSearch" name="cmdSearch" value="Search" alt="Run
Search" />






Output:




   

Monday, 7 October 2013

Converting Gregorian Date To Hijri (Islamic) Date

Sometimes We need to convert the Gregorian Date to Islamic Date. We can do this by CultureInfo class of Globalization

Step 1: The markup

Enter Gregorian Date: <asp:TextBox ID="txtDate" runat="server"></asp:TextBox>
    <br />  
        <asp:Button ID="btnCheck" runat="server" Text="Check"
            onclick="btnCheck_Click" />
            <br />           
    <asp:label ID="lblDate" runat="server" text=""></asp:label>


Step 2: Write the Following Code on Button Click event.

using System.Globalization;
protected void btnCheck_Click(object sender, EventArgs e)
    {      
        CultureInfo arSA = CultureInfo.CreateSpecificCulture("ar-SA");
        string[] arrDt = txtDate.Text.Split('/');
        int dd = Convert.ToInt32(arrDt[0]);
        int mm = Convert.ToInt32(arrDt[1]);
        int yy=Convert.ToInt32(arrDt[2]);
        DateTime dt = new DateTime(yy,mm,dd);
        string s = dt.ToString("dd/MM/yyyy", arSA);
        lblDate.Text = "The Hijri Date is " +
s;
    }


Output:

Tuesday, 1 October 2013

Setting the Dropdown Text which is not displayed in dropdown items in Asp.net

Many times we need to show the Text in the Dropdown but we need to stop the user from selecting it from the item list.
So here is the simple javascript to do the same.

Step 1: Page Markup

<h3>DropdownList Example</h3>
        Gender: <asp:DropDownList ID="ddlCheck" runat="server">  </asp:DropDownList>

  

Step 2: Code to bind the Dropdown

 ddlCheck.Items.Clear();
 ddlCheck.Items.Add("Select Gender");
 ddlCheck.Items.Add("Male");
 ddlCheck.Items.Add("Female");
 


Step 3: Now to Hide the 0th Item i.e "Select Gender" from the dropdownlist, write the following after binding the dropdownlist

 ddlCheck.Items[0].Attributes.Add("style", "display:none");


Output:


Monday, 23 September 2013

Interview Questions & Answers

Q) What is the use of Global.asax File?

A) 
The Global.asax, also known as the ASP.NET application file, is used to serve application-level and session-level events.
There Application level events Application_Start,Application_End and Application_Error to handle the events and execute the code when Application starts  like initializing global

variables and terminating the database connection when application ends, also to handle the Error in Application_error event.
There Session level events like Session_start and Session_end to handle user level code.



Q) What is the difference between Response.Write and Response.Output.Write?

A) 
Response.Write() and Response.Output.Write() both are used for print output on the screen.
But they differ in the following aspects:
1. Response.Output.Write()  allows us to print formatted output but Response.Write() can't print formatted output.
Example:

Response.Output.Write(".Net{0},"ASP"); // Its Correct

Response.Write(".Net{0},"ASP"); // Its Wrong

2. As Per Asp.Net 3.5, Response.Write() Has 4 overloads, with Response.Output.Write()
has 17 overloads


Q) Can we have more than 1 machine.config file?
A)No. There can be only one machine.config file in a website.


Q) Difference of custom control and user control?
A)
Custom Control:

  1. A loosely coupled control w.r.t code and UI
  2. Derives from Control                                  
  3. Defines UI in a ResourceDictionary
    UI is skinable
  4. Has dynamic layout
    UI can be changed in different projects
    Has full toolbox support
  5. Defines a single control
  6. More flexible                                              

==============

User Control:


  1. A tightly coupled control w.r.t code and UI
  2. Derives from UserControl
  3. Defines UI as normal XAML
    Child controls are skinable
  4. Has static layout
    UI is fixed and can't have different looks in different project
    Can't be added to the toolbox
  5. Defines a set of controls
  6. Not very flexible like a Custom Control

Q) How custom controls are compiled?
A) Custom controls are deployed as individual assemblies. They are compiled into a dynamic link library (DLL) and used as any other ASP.Net server control.  

= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =





Q) What is the use of "USE" keyword in sql?
A) It is use to access database object
Example: use databaseName


Q) When will you use outer join in SQL?
A) Use the SQL OUTER JOIN whenever multiple tables must be accessed through a SQL SELECT statement and results should be returned independent of matching criteria between the JOINed tables.


Q) What is meant by SELECTION,PROJECTION,INTERSECTION and EXCEPT in sql?
A)

SELECT ID, NAME  FROM PRODUCTS  WHERE PRICE > 100;
Selection: The selection to the filter you define in your where clause, here the selection corresponds to the price filter


Projection: The projection corresponds to the columns you select, Here the projection corresponds to the ID and NAME columns.

Intersection:  It is used to get common rows from multiple queries, it mostly gives same output as of inner join but the order and number of columns selected in each query should be same and the datatypes should be compatible.
 
Example: use AdventureWorks

SELECT VendorID,ModifiedDate FROM Purchasing.VendorContact
INTERSECT
SELECT VendorID,ModifiedDate FROM Purchasing.VendorAddress

Except: EXCEPT returns any distinct values from the left query that are not also found on the right query, i.e it gives difference of rows from both the queries.
Example: 

USE AdventureWorks;
GO
SELECT ProductID FROM Production.Product
EXCEPT
SELECT ProductID FROM Production.WorkOrder

Q) What will be the output of the following query:
select mst_country.countryname,mst_state.statename from mst_country,mst_state.

A) It will cross join the Countryname with each statename from the respective table.
The query is same as the following:
select mst_country.countryname,mst_state.statename from mst_country CROSS JOIN mst_state

Thursday, 12 September 2013

Reading Excel File And Showing on Gridview in Asp.net

Hello Friends!
Today we will learn how to read the uploaded excel file and load it's data in your webpage.
We can show the contents of the excel file in any control whether it is Gridview or simple Textbox.

Step 1: To Start with, create a Webpage named Excel.aspx and write the Following mark up on the page.

         
           <div>
            <br />  <br />
            <table width="60%" align="center">
            <tr> <th colspan="2" align="center"><h3>Read Excel File </h3> </th> </tr>
            <tr> <th> Upload File </th>
            <td> <asp:FileUpload ID="FileUpload1" runat="server" />  </td>   </tr>
            
            <tr>  <td colspan="2" align="center" > 
            <asp:Button ID="btnUpload" runat="server" 
                    Height="21px" Text="Read..." Width="92px" onclick="btnUpload_Click"/> </td>   </tr>
            </table>    </div>
        <br />  

  <table width="40%" align="center">
            <tr>  <td>
        <asp:GridView ID="GridView1" runat="server" BackColor="White" BorderColor="#CCCCCC" 
                    BorderStyle="None" BorderWidth="1px" CellPadding="3">
            <FooterStyle BackColor="White" ForeColor="#000066" />
            <RowStyle ForeColor="#000066" />
            <PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left" />
            <SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" />
            <HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" />
        </asp:GridView>
       </td> </tr>     </table>


Step 2: We will need the namespace  System.Data.OleDb as follows

          using System.Data.OleDb;
          using System.IO;

Step 3: Now add the following code on the btnUpload_Click Event.

      protected void btnUpload_Click(object sender, EventArgs e)
    {
        string connectionString = "";
        if (FileUpload1.HasFile)
        {
            string fileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
            string fileExtension = Path.GetExtension(FileUpload1.PostedFile.FileName);
            string fileLocation = Server.MapPath("~/App_Data/" + fileName);
            FileUpload1.SaveAs(fileLocation);

            //Check whether file extension is xls or xslx

            if (fileExtension == ".xls")
            {
                connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileLocation + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
            }
            else if (fileExtension == ".xlsx")
            {
                connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileLocation + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
            }

            //Create OleDB Connection and OleDb Command

            OleDbConnection con = new OleDbConnection(connectionString);
            OleDbCommand cmd = new OleDbCommand();
            cmd.CommandType = System.Data.CommandType.Text;
            cmd.Connection = con;
            OleDbDataAdapter dAdapter = new OleDbDataAdapter(cmd);
            DataTable dtExcelRecords = new DataTable();
            con.Open();
            DataTable dtExcelSheetName = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
            string getExcelSheetName = dtExcelSheetName.Rows[0]["Table_Name"].ToString();
            cmd.CommandText = "SELECT * FROM [" + getExcelSheetName + "]";
            dAdapter.SelectCommand = cmd;
            dAdapter.Fill(dtExcelRecords);
            con.Close();
           

            GridView1.DataSource = dtExcelRecords;
            GridView1.DataBind();
        }
    }


Output:





Wednesday, 31 July 2013

Encrypt and Decrypt with and without key

Today we'll see how to Encrypt and Decrypt with and without key in asp.net

Step 1 :Add class file in app code folder


Step 2: We are going to use Cryptography  so add in class file,

using System.Security.Cryptography;

using System.Text;



    public static string Key
    {
        set
        {
            _key = value;
        }
    }

    /// <summary>
    /// Encrypt the given string using the default key.
    /// </summary>
    /// <param name="strToEncrypt">The string to be encrypted.</param>
    /// <returns>The encrypted string.</returns>
    public static string Encrypt(string strToEncrypt)
    {
        try
        {
            return Encrypt(strToEncrypt, _key);
        }
        catch (Exception ex)
        {
            return "Wrong Input. " + ex.Message;
        }

    }

    /// <summary>
    /// Decrypt the given string using the default key.
    /// </summary>
    /// <param name="strEncrypted">The string to be decrypted.</param>
    /// <returns>The decrypted string.</returns>
    public static string Decrypt(string strEncrypted)
    {
        try
        {
            return Decrypt(strEncrypted, _key);
        }
        catch (Exception ex)
        {
            return "Wrong Input. " + ex.Message;
        }
    }

    /// <summary>
    /// Encrypt the given string using the specified key.
    /// </summary>
    /// <param name="strToEncrypt">The string to be encrypted.</param>
    /// <param name="strKey">The encryption key.</param>
    /// <returns>The encrypted string.</returns>
    public static string Encrypt(string strToEncrypt, string strKey)
    {
        try
        {
            TripleDESCryptoServiceProvider objDESCrypto = new     TripleDESCryptoServiceProvider();
            MD5CryptoServiceProvider objHashMD5 = new MD5CryptoServiceProvider();

            byte[] byteHash, byteBuff;
            string strTempKey = strKey;

            byteHash = objHashMD5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(strTempKey));
            objHashMD5 = null;
            objDESCrypto.Key = byteHash;
            objDESCrypto.Mode = CipherMode.ECB; //CBC, CFB

            byteBuff = ASCIIEncoding.ASCII.GetBytes(strToEncrypt);
            return Convert.ToBase64String(objDESCrypto.CreateEncryptor().TransformFinalBlock(byteBuff, 0, byteBuff.Length));
        }
        catch (Exception ex)
        {
            return "Wrong Input. " + ex.Message;
        }
    }


    
    /// Decrypt the given string using the specified key.
   
    /// <param name="strEncrypted">The string to be decrypted.</param>
    /// <param name="strKey">The decryption key.</param>
    /// <returns>The decrypted string.</returns>
    public static string Decrypt(string strEncrypted, string strKey)
    {
        try
        {
            TripleDESCryptoServiceProvider objDESCrypto = new TripleDESCryptoServiceProvider();
            MD5CryptoServiceProvider objHashMD5 = new MD5CryptoServiceProvider();

            byte[] byteHash ;
            byte[] byteBuff ;
            string strTempKey = strKey;

            byteHash = objHashMD5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(strTempKey));
            objHashMD5 = null;
            objDESCrypto.Key = byteHash;
            objDESCrypto.Mode = CipherMode.ECB; //CBC, CFB

            byteBuff = Convert.FromBase64String(strEncrypted);
            string strDecrypted = ASCIIEncoding.ASCII.GetString(objDESCrypto.CreateDecryptor().TransformFinalBlock(byteBuff, 0, byteBuff.Length));
            objDESCrypto = null;

            return strDecrypted;
        }
        catch (Exception ex)
        {
            return "Wrong Input. " + ex.Message;
        }
    }

}

3 step: Add default.aspx

<div>
    
        <asp:CheckBox ID="chkIsCustomKey" runat="server" 
            oncheckedchanged="chkIsCustomKey_CheckedChanged" Text="Use my custom key" 
            AutoPostBack="True" />
        <br />
        <br />
        <br />
        <br />
        <asp:Label ID="Label1" runat="server" Text="Custom Key"></asp:Label>
&nbsp;&nbsp;<asp:TextBox ID="txtCustomKey" runat="server" Height="18px" Width="279px"></asp:TextBox>
        <br />
        <br />
        <asp:Label ID="Label2" runat="server" Text="Input text"></asp:Label>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        <asp:TextBox ID="txtInputText" runat="server" Height="61px" Width="279px"></asp:TextBox>
        <br />
        <br />
        <br />
        <br />
        <br />
        <br />
        <asp:Label ID="Label3" runat="server" Text="OutPut Text"></asp:Label>
&nbsp;&nbsp;
        <asp:TextBox ID="txtOutputText" runat="server" Height="76px" Width="276px" ReadOnly="True"></asp:TextBox>
        <br />
        <br />
        <br />
        <asp:Button ID="Button1" runat="server" onclick="Button1_Click" 
            Text="Encrypt" />
&nbsp;&nbsp;&nbsp;
        <asp:Button ID="Button2" runat="server" onclick="Button2_Click" 
            Text="Decrypt" />
        &nbsp;&nbsp;
        <asp:Button ID="Button3" runat="server" onclick="Button3_Click" Text="Clear" />
        <br />
        <br />
    

    </div>

step 4: In default.aspx.cs

 ON Page_Load()
    {
        txtCustomKey.Enabled = false;
    }
  private string SetKey()
        {
            if (chkIsCustomKey.Checked)
            {
                if (txtCustomKey.Text != String.Empty)
                {
                    return txtCustomKey.Text;
                }
                else
                {
                    return "SampleKey";
                }
            }
            else
            {
                return "SampleKey";
            }
        }
     btnEncrypt_Click()
      {
          txtOutputText.Text = Class1.Encrypt(txtInputText.Text, SetKey());
            
      }
     btnDecrypt_Click()
      {

          txtOutputText.Text = Class1.Decrypt(txtInputText.Text, SetKey());
       
      }
   btnClear_Click()
      {
          chkIsCustomKey.Checked = false;
          txtCustomKey.Text = String.Empty;
          txtCustomKey.Enabled = false;
          txtInputText.Text = String.Empty;
          txtOutputText.Text = String.Empty;
      }


     chkIsCustomKey_CheckedChanged()
      {
          if (chkIsCustomKey.Checked)
          {
              txtCustomKey.Enabled = true;
          }
          else
          {
              txtCustomKey.Enabled = false;
              txtCustomKey.Text = string.Empty;
          }

      }

OUTPUT:



Monday, 29 July 2013

Ajax CascadingDropDown using webservice

Ajax CascadingDropDown




Today will see how to use Ajax Cascading DropDown in asp.net

1 step: Add ajaxcontol tool kit in your visual studio toolbox  .Here my scenario is, there will be three drop down CATEGORY,SUBCATEGORY,PRODUCT .

FOR this we have three tables in database

2 step: Drag n Drop Three asp DropDownList and ajax CascadingDropDown and SCRIPTMANAGER.

  

<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server"> </asp:ToolkitScriptManager>
   
   <div>

          ProductCategory

        <asp:DropDownList  ID="DDlcategory" runat="server">
        </asp:DropDownList>

  <asp:CascadingDropDown ID="CascadingDropDown1" TargetControlID="DDlcategory" Category="ProductCategory"   PromptText="Select ProductCategory" LoadingText="Loading ProductCategory.." ServiceMethod="BindCategoryDetails" ServicePath="~/CascadingDropdown.asmx"  runat="server">
          </asp:CascadingDropDown>

          <br />
          <br />
          ProductSubCategory&nbsp;&nbsp;&nbsp; 
         <asp:DropDownList  ID="DDlsubcategory" runat="server">
         </asp:DropDownList>
          <br />
          <br />
          Product&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp

          <asp:CascadingDropDown ID="CascadingDropDown2" TargetControlID="DDlsubcategory"  Category="Productsubcategory" ParentControlID="DDlcategory"  PromptText="Select Productsubcategory" LoadingText="Loading subcategory.." ServiceMethod="BindProductSubCategory" ServicePath="~/CascadingDropdown.asmx"  runat="server">
          </asp:CascadingDropDown>

        <asp:DropDownList ID="DDlproduct" runat="server">
        </asp:DropDownList>

        <asp:CascadingDropDown ID="CascadingDropDown3" TargetControlID="DDlproduct"  Category="Product" ParentControlID="DDlsubcategory"  PromptText="Select Product" LoadingText="Loading product.." ServiceMethod="BindProduct" ServicePath="~/CascadingDropdown.asmx"  runat="server">
          </asp:CascadingDropDown>

    </div>


3 step : Now add webservices in .cs file
             here we have to write 3 web method in web services. Please note you can change method    name reset of all will be same.

1) for Category

  [WebMethod]
 public CascadingDropDownNameValue[] BindCategoryDetails(string knownCategoryValues, string category)
    {

        
        SqlDataAdapter daCat = new SqlDataAdapter("select * from Tbl_ProductCategory", con);
        DataSet dsCat = new DataSet();
        daCat.Fill(dsCat);
    
        //create list and add items in it by looping through dataset table
        List<CascadingDropDownNameValue> catdetails = new List<CascadingDropDownNameValue>();
        foreach (DataRow dtrow in dsCat.Tables[0].Rows)
        {
            string ProdCategoryID = dtrow["ProdCategoryID"].ToString();
            string ProductCategoryName = dtrow["ProductCategoryName"].ToString();
            catdetails.Add(new CascadingDropDownNameValue(ProductCategoryName,ProdCategoryID));
        }
        return catdetails.ToArray();
    }

2) for subcategory
 [WebMethod]
    public CascadingDropDownNameValue[] BindProductSubCategory(string knownCategoryValues, string category)
    {
        int ProdCategoryID;
        //This method will return a StringDictionary containing the name/value pairs of the currently selected values
        StringDictionary ProdCategory = AjaxControlToolkit.CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues);
        ProdCategoryID = Convert.ToInt32(ProdCategory["ProductCategory"]);
        con.Open();
        SqlCommand cmdProdCat = new SqlCommand("select * from Tbl_ProductSubCategory where ProdCategoryID=@ProdCategoryID", con);
        cmdProdCat.Parameters.AddWithValue("@ProdCategoryID", ProdCategoryID);
        cmdProdCat.ExecuteNonQuery();
        SqlDataAdapter daProdCategory = new SqlDataAdapter(cmdProdCat);
        DataSet dsProdCat = new DataSet();
        daProdCategory.Fill(dsProdCat);
        con.Close();
        //create list and add items in it by looping through dataset table
        List<CascadingDropDownNameValue> SubCategorydetails = new List<CascadingDropDownNameValue>();
        foreach (DataRow dtrow in dsProdCat.Tables[0].Rows)
        {
            string ProdSubCategoryID = dtrow["ProdSubCategoryID"].ToString();
            string ProductSubCategoryName = dtrow["ProductSubCategoryName"].ToString();
            SubCategorydetails.Add(new CascadingDropDownNameValue(ProductSubCategoryName, ProdSubCategoryID));
        }
        return SubCategorydetails.ToArray();

    }
3) for product

 [WebMethod]
    public CascadingDropDownNameValue[] BindProduct(string knownCategoryValues, string category)
    {
        int ProductID;
        //This method will return a StringDictionary containing the name/value pairs of the currently selected values
        StringDictionary Product = AjaxControlToolkit.CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues);
        ProductID = Convert.ToInt32(Product["Productsubcategory"]);
        con.Open();
        SqlCommand cmdProduct = new SqlCommand("select * from tblProduct where ProdSubCategoryID=@ProdSubCategoryID", con);
        cmdProduct.Parameters.AddWithValue("@ProdSubCategoryID", ProductID);
        cmdProduct.ExecuteNonQuery();
        SqlDataAdapter daProduct = new SqlDataAdapter(cmdProduct);
        DataSet dsProduct = new DataSet();
        daProduct.Fill(dsProduct);
        con.Close();
        //create list and add items in it by looping through dataset table
        List<CascadingDropDownNameValue> Productdetails = new List<CascadingDropDownNameValue>();
        foreach (DataRow dtrow in dsProduct.Tables[0].Rows)
        {
            string ProductId = dtrow["ProductId"].ToString();
            string ProductName = dtrow["ProductName"].ToString();
            Productdetails.Add(new CascadingDropDownNameValue(ProductName, ProductId));
        }
        return Productdetails.ToArray();
    }

Saturday, 27 July 2013

J query Accordion using nested repeater control


               Follow Me To get Health tip's and bodybuilding
instagram:sayyedtanveer1410



J query Accordion using nested repeater control in asp.net



    OUT PUT

Step 1: Create database 



Second Step: Open visual studio add default.aspx page

IN HEAD TAG:

<style type="text/css">
     .topnav
        {
            width: 213px;
            padding: 40px 28px 25px 0;
            font-family: "CenturyGothicRegular" , "Century Gothic" , Arial, Helvetica, sans-serif;
        }
        
        ul.topnav
        {
            padding: 0;
            margin: 0;
            font-size: 1em;
            line-height: 0.5em;
            list-style: none;
        }
        
        ul.topnav li
        {
        }
        
        ul.topnav li a
        {
            line-height: 10px;
            font-size: 11px;
            padding: 10px 5px;
            color: Aqua;
            display: block;
            text-decoration: none;
            font-weight: bolder;
        }
        
        ul.topnav li a:hover
        {
            background-color: #675C7C;
            color: white;
        }
        
        ul.topnav ul
        {
            margin: 0;
            padding: 0;
            display: none;
        }
        
        ul.topnav ul li
        {
            margin: 0;
            padding: 0;
            clear: both;
        }
        
        ul.topnav ul li a
        {
            padding-left: 20px;
            font-size: 11px;
            font-weight: normal;
            outline: 0;
        }
        
        ul.topnav ul li a:hover
        {
            
            background-color: #D3C99C;
            font-family:Lucida Sans;
            color: #675C7C;
        }
        
        ul.topnav ul ul li a
        {
            color:Yellow;
            font-weight:bold;
             font-family:Lucida Sans;
            
            padding-left: 40px;
        }
        
        ul.topnav ul ul li a:hover
        {
            background-color: #D3CEB8;
            color:Red;
        }
        
        ul.topnav span
        {
            float: right;
        }
    </style>
 <script type="text/javascript" src="Scripts/jquery-1.5.2.min.js"></script>
 <script type="text/javascript" src="Scripts/scriptbreaker-multiple-accordion-1.js">DownLoad</script>

    <script language="JavaScript" type="text/javascript">
        $(document).ready(function () {
            $("#div").accordion({
                accordion: false,
                speed: 500,
                closedSign: '[+]',
                openedSign: '[-]'
            });
            $('.topnav ul:first').show(); 
            

        });
    </script>

IN BODY TAG: HERE WE NEED TO ADD THREE REPEATER CONTROL AND HIDDEN FIELD .

 <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
    <asp:UpdatePanel runat="server" UpdateMode="Conditional">
        <ContentTemplate>
            <div id="div">
                <ul class="topnav">
                    <asp:Repeater ID="parentRepeater" runat="server">
                        <ItemTemplate>
                            <li id="liFirst" style="background-color:Gray;"><a href="#">
                                <%# DataBinder.Eval(Container.DataItem, "ProductCategoryName")%></a>
                                <asp:HiddenField ID="ItemID" Value='<%#Eval("ProdCategoryID")%>' runat="server" Visible="false" />
                                <!-- start child repeater -->
                                <div style="height: auto;">
                                    <p style="margin-left: -29px;">
                                        <ul>
                                            <asp:Repeater ID="childRepeater" runat="server">
                                                <ItemTemplate>
                                                    <li><a href="#">
                                                        <%# DataBinder.Eval(Container.DataItem, "ProductSubCategoryName")%></a>
                                                        <br>
                                                        <ul>
                                                            <asp:Repeater ID="nestchildRepeater" runat="server">
                                                                <ItemTemplate>
                                                                    <li>
                                                                        <asp:HiddenField ID="ChildID" Value='<%#Eval("ProdSubCategoryID")%>' runat="server"
                                                                            Visible="false" />
                                                                        <asp:LinkButton ID="lnkBtnProducts" Text='<%# DataBinder.Eval(Container.DataItem, "ProductName")%>'
                                                                            runat="server" />
                                                                    </li>
                                                                </ItemTemplate>
                                                            </asp:Repeater>
                                                        </ul>
                                                    </li>
                                                </ItemTemplate>
                                            </asp:Repeater>
                                        </ul>
                                    </p>
                                </div>
                                <!-- end child repeater -->
                            </li>
                        </ItemTemplate>
                    </asp:Repeater>
                    <!-- end parent repeater -->
                </ul>
            </div>
        </ContentTemplate>

    </asp:UpdatePanel>

3 Step: In default.aspx.cs on PageLoad ()

if (!IsPostBack)
        {
            // MY CATEGORY TABLE
            SqlDataAdapter cmd1 = new SqlDataAdapter("select * from Tbl_ProductCategory", con);
            DataSet ds = new DataSet();
            cmd1.Fill(ds, "Tbl_ProductCategory");

            // MY SUB CATEGORY TABLE
            SqlDataAdapter cmd2 = new SqlDataAdapter("select * from Tbl_ProductSubCategory", con);
            cmd2.Fill(ds, "Tbl_ProductSubCategory");

            // MY PRODUCT TABLE
            SqlDataAdapter cmd3 = new SqlDataAdapter("select * from tblProduct", con);
            cmd3.Fill(ds, "tblProduct");

            // bind parentRepeater... means Category eg cake
            parentRepeater.DataSource = ds.Tables["Tbl_ProductCategory"];
            parentRepeater.DataBind();

            // Now Check In parentRepeater To bind Child Repeater ...means subcategory of that category eg cake -> celebration cake
            foreach (RepeaterItem Item in parentRepeater.Items)
            {
               
                HiddenField hidden = (HiddenField)parentRepeater.Items[Item.ItemIndex].FindControl("ItemID");
               
                DataView dv = new DataView(ds.Tables["Tbl_ProductSubCategory"]);
                dv.RowFilter = "ProdCategoryID= " + Convert.ToInt32(hidden.Value);

                Repeater nestedDataList = (Repeater)parentRepeater.Items[Item.ItemIndex].FindControl("childRepeater");
                nestedDataList.DataSource = dv;
                nestedDataList.DataBind();

                // Now Check In ChildRepeater To bind NestedRepeater ...means Product of that Subcategory eg cake -> celebration cake -> blackforest
               
                foreach (RepeaterItem NestItem in nestedDataList.Items)
                {

                    HiddenField Nesthidden = (HiddenField)nestedDataList.Items[Item.ItemIndex].FindControl("ChildID");
                    
                    DataView dvNest = new DataView(ds.Tables["tblProduct"]);
                    dvNest.RowFilter = "ProdSubCategoryID= " + Convert.ToInt32(hidden.Value);
                    
                    Repeater nestedProdDataList = (Repeater)nestedDataList.Items[NestItem.ItemIndex].FindControl("nestchildRepeater");
                    nestedProdDataList.DataSource = dvNest;
                    nestedProdDataList.DataBind();
                }

            }
            con.Close();

        }

Enjoy ....