How To Create TextBox Dynamically using Jquery t and Read Control Value In Code Behind

<%@ 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>

    <script src="Scripts/jquery-1.3.2.js" type="text/javascript"></script>

    <script type="text/javascript">
        $(document).ready(function() {
            $("#btnOfficial").click(function() {
                var hdValue = $("#theValue");
                var num = ($("#theValue").val() - 1) + 2;
                hdValue.val(num);
                var newDiv = $(document.createElement('div')).attr("id", 'my' + num + 'Div');
                newDiv.after().html('<input type="text"  name="TextBox' + num + '" value="TextBox' + num + '" >');
                newDiv.appendTo("#Div1");

            });
        });
    </script>

</head>
<body>
    <form id="form1" runat="server">
    <div id="Div1">
    </div>
    <asp:GridView ID="GridView1" runat="server">
    </asp:GridView>
    <input type="button" id="btnOfficial" value="Add Another TextBox" />
    <input type="hidden" value="1" id="theValue" runat="server" />
    <asp:Button ID="btnSave" runat="server" Text="Read" OnClick="btnSave_Click" />
    </form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;

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


    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        List<string> alForm = new List<string>();
        //Textbox id is started
        // with 2 like(TextBox2,TextBox3.....
        for (int i = 2; i < Request.Form.Count - 2; i++)
        {
            string strId = "TextBox" + i.ToString();
            string strValue = Request.Form[strId].ToString();
            alForm.Add(strValue);
            strValue = "";


        }
        //Uncomment this line and test.
        //foreach (string x in Request.Form)
        //{

        //   string strValue = Request.Form[x].ToString();
        //  alForm.Add(strValue);

        //}
        GridView1.DataSource = alForm;
        GridView1.DataBind();
    }
}

Dynamic Drag’n Drop With jQuery And ASP.NET

Photobucket In thi post i will show how to drag’n drop & saving the new positions to the database. Here is, how it is done by using jQuery & jQuery UI:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="Default2" %>

<!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>

   <script src="Scripts/jquery-1.3.2.js" type="text/javascript"></script>

   <script type="text/javascript" src="Scripts/jquery-ui-1.7.2.custom.min.js"></script>

   <script type="text/javascript">
       $(document).ready(function() {
           $("#contentLeft ul").sortable({ opacity: 0.6, cursor: 'move', update: function() {
               var order = $(this).sortable("toArray");
               $.ajax(
                   {
                       type: "POST",
                       url: "Default.aspx/Update",
                       data: "{'NewOrder': '" + order + "'}",
                       dataType: "json",
                       contentType: "application/json"

                   });
           }

           });

       });   
   </script>

   <style type="text/css">
       .itemStyle
       {
           background-color: #c0c0c0;
           font-family: Verdana;
           list-style: none;
       }
       .alter
       {
           background-color: #000fff;
           font-family: Verdana;
           list-style: none;
       }
       .contentLeft
       {
           height: 100%;
           width: 300px;
           overflow: auto;
       }
   </style>
</head>
<body>
   <form id="form1" runat="server">
   <div id="contentLeft" class="contentLeft">
       <asp:Repeater ID="rptLan" runat="server">
           <HeaderTemplate>
               <ul>
           </HeaderTemplate>
           <ItemTemplate>
               <li id="<%#Eval("ID")%>" class="itemStyle">
                   <%#Eval("Name")%></li>
           </ItemTemplate>
           <AlternatingItemTemplate>
               <li id="<%#Eval("ID")%>" class="alter">
                   <%#Eval("Name")%></li>
           </AlternatingItemTemplate>
           <FooterTemplate>
               </ul>
           </FooterTemplate>
       </asp:Repeater>
   </div>
   <div id="divRight">
   </div>
   </form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections.Specialized;

public partial class Default2 : System.Web.UI.Page
{
   protected void Page_Load(object sender, EventArgs e)
   {
       DemoDataContext db = new DemoDataContext();
       var query = from c in db.demos
                   orderby c.Order
                   select c;
       rptLan.DataSource = query;
       rptLan.DataBind();

   }
   /// <summary>
   /// Page Method for updating order
   /// </summary>
   /// <param name="NewOrder"></param>
   [System.Web.Services.WebMethod]
   public static void Update(string NewOrder)
   {
       DemoDataContext db = new DemoDataContext();
       int listingCounter = 1;
       foreach (var item in NewOrder.Split(','))
       {
           demo demo = db.demos.Single(x => x.ID == int.Parse(item.ToString()));
           demo.Order = listingCounter;
           db.SubmitChanges();
           listingCounter++;

       }
   }
}
{{Download}}

How To Use Jquery Google Chart In asp.net

In this post i will show how to add Jquery Google Chart in asp.net. Click Here to download Jquery Google Chart Plugin
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Chart.aspx.cs" Inherits="Chart" %>

<!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>jQuery Google Chart Demo</title>

    <script src="jquery-1.3.2.min.js" type="text/javascript"></script>

    <script src="jgcharts.pack.js" type="text/javascript"></script>

    <link href="Style/style.css" rel="stylesheet" type="text/css" />

    <script type="text/javascript">
        $(document).ready(function() {
            $("#btnCreate").click(function() {
                $("#bar_chart").html("");
                var api = new jGCharts.Api();
                var opt =
            {
                data: eval($("[id$='hdValue']").val()),
                axis_labels: ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'],
                legend: ['X', 'Y'],
                size: '600x335',
                type: $("[id$='ddlType']").val(),
                bg: $("[id$='ddlColor']").val(),
                bar_width: 15
            };
                jQuery('<img>').attr('src', api.make(opt)).appendTo("#bar_chart");
            });
        });
    </script>

    <style type="text/css">
        .style1
        {
            width: 100%;
        }
    </style>
</head>
<body>
    <form id="dform" runat="server">
    <div class="right">
        <h4>
            Demo Chart</h4>
        <div id="bar_chart">
        </div>
        <div id="bar_chart_data">
        </div>
    </div>
    <div class="left">
        <asp:HiddenField ID="hdValue" runat="server" />
        <asp:GridView ID="gvChart" runat="server" AutoGenerateColumns="false">
            <Columns>
                <asp:BoundField DataField="X" HeaderText="X" />
                <asp:BoundField DataField="Y" HeaderText="Y" />
            </Columns>
        </asp:GridView>
    </div>
    <table style="width: 50%; margin-top: 40%;">
        <tr>
            <td>
                Chart Type
            </td>
            <td>
                <asp:DropDownList ID="ddlType" runat="server">
                    <asp:ListItem Value="stripes">Stripes</asp:ListItem>
                    <asp:ListItem Value="p">Pie</asp:ListItem>
                    <asp:ListItem Value="p3">Pie3D</asp:ListItem>
                    <asp:ListItem Value="lc">Line</asp:ListItem>
                    <asp:ListItem Value="bhs">Stacked Bar</asp:ListItem>
                </asp:DropDownList>
            </td>
        </tr>
        <tr>
            <td>
                Background Color
            </td>
            <td>
                <asp:DropDownList ID="ddlColor" runat="server">
                    <asp:ListItem Text="Red" Value="FF0000"></asp:ListItem>
                    <asp:ListItem Text="Light Blue" Value="0000FF"></asp:ListItem>
                    <asp:ListItem Text="Light Purple" Value="FF0080"></asp:ListItem>
                    <asp:ListItem Text="Light Gray" Value="C0C0C0"></asp:ListItem>
                </asp:DropDownList>
            </td>
        </tr>
        <tr>
            <td>
                &nbsp;
            </td>
            <td>
                <input type="button" id="btnCreate" value="Create" />
            </td>
        </tr>
    </table>
    </form>
</body>
</html>
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class Chart : System.Web.UI.Page
{
    private DataTable GetSampleData()
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("X");
        dt.Columns.Add("Y");
        dt.Rows.Add("1000", "3003.55");
        dt.Rows.Add("1000", "72.65");
        dt.Rows.Add("1000", "760.89");
        dt.Rows.Add("1000", "354.55");
        dt.Rows.Add("1000", "180.52");
        dt.Rows.Add("1000", "408.54");
        return dt;

    }
    protected void Page_Load(object sender, EventArgs e)
    {
        DataTable dt = GetSampleData();
        gvChart.DataSource = dt;
        gvChart.DataBind();

        ArrayList chartData = new ArrayList();
        foreach (DataRow dr in dt.Rows)
        {
            chartData.Add(String.Format("[{0}, {1}]", dr[0], dr[1].ToString().Replace("-", "")));
        }

        //Convert .NET Array to JS Array
        string ReturnValue = String.Empty;
        for (int i = 0; i < chartData.Count; i++)
        {
            ReturnValue += chartData[i];
            if (i != chartData.Count - 1)
                ReturnValue += ",";
        }

        //Data is returned in the following format: 
        //[[X, Y]

        hdValue.Value = String.Format("[{0}]", ReturnValue);

    }
}
{{download}}

How to use Generic Delegate in C#


Action<T>:Encapsulates a method that takes a single parameter and does not return a value.
Action<T1,T2>:Encapsulates a method that has two parameters and does not return a value.
Action<T1,T2,T3>:Encapsulates a method that has three and does not return a value.
Action<T1,T2,T3,T4>:Encapsulates a method that has four and does not return a value.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace GenericDelegate
{
 class Program
 {
     static void Main(string[] args)
     {
         //Action<T>
         Action print = s => Console.WriteLine(s);
         string message = "Hello World";
         print(message);

         //Action<T1,T2>
         Action add = (x, y) => Console.WriteLine(x+y);
         add(1, 2);
       


     }
 }
}


How To Add Jquery Plugin Tablesorter in Gridview

<%@ 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>

    <script src="Scripts/jquery-1.3.2.js" type="text/javascript"></script>

    <script src="Scripts/Jquery.tablesorter.js" type="text/javascript"></script>

    <script type="text/javascript">
        $(document).ready(function() {
            $("#grdStudent").tablesorter();
        }
        ); 
    
    </script>

</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="grdStudent" runat="server" UseAccessibleHeader="true">
        </asp:GridView>
    </div>
    </form>
</body>
</html>
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 void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            grdStudent.DataSource = new Student().GetAll();
            grdStudent.DataBind();
            MakeAccessible(grdStudent);
        }

    }

    private void MakeAccessible(GridView grid)
    {
        if (grid.Rows.Count > 0)
        {
            //This replaces <td> with <th> and adds the scope attribute
            grid.UseAccessibleHeader = true;

            //This will add the <thead> and <tbody> elements
            grid.HeaderRow.TableSection = TableRowSection.TableHeader;

            //This adds the <tfoot> element. Remove if you don't have a footer row
            grid.FooterRow.TableSection = TableRowSection.TableFooter;
        }
    }
}
public class Student
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }
    public List<Student> GetAll()
    {
        List<Student> list = new List<Student>()
        {
            new Student{FirstName="S001",LastName="L01",Age=21},
            new Student{FirstName="S002",LastName="L21",Age=31},
            new Student{FirstName="S003",LastName="L341",Age=51},
            new Student{FirstName="S004",LastName="L021",Age=51},
            new Student{FirstName="S005",LastName="L0231",Age=45},
            new Student{FirstName="S006",LastName="L0231",Age=26},
            new Student{FirstName="S007",LastName="L021",Age=14},
            new Student{FirstName="S008",LastName="L5401",Age=21},
            new Student{FirstName="S009",LastName="L231",Age=21},
            new Student{FirstName="S009",LastName="L0231",Age=21},
            new Student{FirstName="S011",LastName="L0231",Age=21},

        };

        return list;
    }

}
Before using this code read this article How To Make GridView Control Accessible {{Download}}

Cascading Dropdownlist using JQuery and WebService

<%@ 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>

  <script src="Scripts/jquery-1.2.6.js" type="text/javascript"></script>

  <script type="text/javascript">
      $().ready(function() {
          $.ajax({
              type: "POST",
              url: "WebService.asmx/GetStates",
              data: "{}",
              contentType: "application/json; charset=utf-8",
              dataType: "json",
              success: function(msg) {
                  BindStateddl(msg.d)
              }
          });
          //Fetch related city
          $("#ddlStates").change(function() {
              var StateID = $("#ddlStates > option[@selected]").attr("value");
              $("#ddlCities").html("");
              $.ajax({
                  type: "POST",
                  url: "WebService.asmx/FindCityByID",
                  data: "{ID:'" + StateID + "'}",
                  contentType: "application/json; charset=utf-8",
                  dataType: "json",
                  success: function(msg) {
                      BindCityddl(msg.d)
                  }
              });
          });
      });
      function BindStateddl(msg) {
          $.each(msg, function() {

              $("#ddlStates").append($("<option></option>").val(this['StateId']).html(this['Name']));

          });
      }
      function BindCityddl(msg) {
          $.each(msg, function() {

              $("#ddlCities").append($("<option></option>").val(this['CityID']).html(this['Name']));

          });
      }
  </script>

</head>
<body>
  <form id="form1" runat="server">
  <div>
      <table>
          <tr>
              <td>
                  State
              </td>
              <td>
                  <asp:DropDownList ID="ddlStates" runat="server">
                      <asp:ListItem Value="0">Select</asp:ListItem>
                  </asp:DropDownList>
              </td>
          </tr>
          <tr>
              <td>
                  Cities
              </td>
              <td>
                  <select id="ddlCities" runat="server">
                  </select>
              </td>
          </tr>
      </table>
  </div>
  </form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

/// <summary>
/// Summary description for WebService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService
{

  /// <summary>
  /// Filter city by StateID
  /// </summary>
  /// <param name="ID"></param>
  /// <returns></returns>
  [WebMethod]
  public List<Cities> FindCityByID(string ID)
  {
      return GetCities().FindAll(x => x.StateId == int.Parse(ID));

  }
  /// <summary>
  /// Return list of cities.
  /// </summary>
  /// <returns></returns>
  public List<Cities> GetCities()
  {
      List<Cities> cities = new List<Cities>()
          {
              new Cities{CityID=1,StateId=1,Name="Lucknow"},
              new Cities{CityID=2,StateId=1,Name="Allahabad"},
              new Cities{CityID=3,StateId=2,Name="Patiala"},
              new Cities{CityID=4,StateId=2,Name="Amritsar"},
              new Cities{CityID=5,StateId=3,Name="Shimla"},
         
          };
      return cities;
  }


  /// <summary>
  /// Return List of states
  /// </summary>
  /// <returns></returns>
  [WebMethod]
  public List<State> GetStates()
  {

      List<State> states = new List<State>()
          {
              new State{StateId=1,Name="UP"},
              new State{StateId=2,Name="Punjab"},
              new State{StateId=3,Name="Himachal"}
          };
      return states;

  }
  /// <summary>
  /// 
  /// </summary>
  public class State
  {
      public int StateId { get; set; }
      public string Name { get; set; }
  }
  /// <summary>
  /// 
  /// </summary>
  public class Cities
  {
      public int CityID { get; set; }
      public int StateId { get; set; }
      public string Name { get; set; }
  }

}

Download

How To display Image using Linq To Sql




Default.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1._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>
       <asp:GridView ID="grdCategories" runat="server" DataKeyNames="CategoryID" Width="600px"
           AutoGenerateColumns="false">
           <Columns>
               <asp:BoundField DataField="CategoryID" HeaderText="CategoryID" />
               <asp:BoundField DataField="CategoryName" HeaderText="CategoryName" />
               <asp:TemplateField>
                   <ItemTemplate>
                       <asp:Image ID="Image1" runat="server" ImageUrl='<%#"ImageHandler.ashx?CategoryID="+ Eval("CategoryID")  %>' />
                   </ItemTemplate>
               </asp:TemplateField>
           </Columns>
       </asp:GridView>
   </div>
   </form>
</body>
</html>

Default.aspx.cs



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

namespace WebApplication1
{
   public partial class _Default : System.Web.UI.Page
   {
       protected void Page_Load(object sender, EventArgs e)
       {
           NorthwindDataContext db = new NorthwindDataContext();
           var cate = from c in db.Categories
                      select new
                      {
                          CategoryName = c.CategoryName,
                          CategoryID = c.CategoryID,
                          Image = c.Picture,
                      };
           grdCategories.DataSource = cate;
           grdCategories.DataBind();
       }
   }
}
ImageHandler.ashx
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Drawing.Imaging;

namespace WebApplication1
{

   public class ImageHandler : IHttpHandler
   {

       public void ProcessRequest(HttpContext context)
       {
           HttpRequest req = context.Request;
           // string categoryID = "1";
           string categoryID = req.QueryString["CategoryID"].ToString();
           // Get information about the specified category
           NorthwindDataContext db = new NorthwindDataContext();
           var category = from c in db.Categories
                          where Convert.ToInt32(c.CategoryID) == Convert.ToInt32(categoryID)
                          select c.Picture;
           int len = category.First().Length;
           // Output the binary data
           // But first we need to strip out the OLE header
           int OleHeaderLength = 78;
           int strippedImageLength = len - OleHeaderLength;
           byte[] imagdata = new byte[strippedImageLength];
           Array.Copy(category.First().ToArray(), OleHeaderLength, imagdata, 0, strippedImageLength);
           if ((imagdata) != null)
           {
               MemoryStream m = new MemoryStream(imagdata);
               System.Drawing.Image image = System.Drawing.Image.FromStream(m);
               image.Save(context.Response.OutputStream, ImageFormat.Jpeg);
           }
       }

       public bool IsReusable
       {
           get
           {
               return false;
           }
       }
   }
}