Archive

Archive for March, 2010

Repeater Paging using Linq

March 29, 2010 3 comments

Hi

try this example for paging Repeater control using Linq

Step1 :- Open VS2008 and create a new website

Step2 :- add new Linq to SQL DataContext  and name it “Northwind.dbml” and add Customers table in it

Step3 :- Add new Web page and from ToolBox drag Repeater control and PlaceHolder control inside page

<asp:Repeater ID="Repeater1" runat="server">
        <HeaderTemplate>
            <table>
        </HeaderTemplate>
        <ItemTemplate>
            <tr>
                <td>
                    <asp:Label runat="server" ID="lblContactName" Text='<%# Eval("Name") %>' />
                </td>
            </tr>
        </ItemTemplate>
        <FooterTemplate>
            </table>
        </FooterTemplate>
    </asp:Repeater>
    <table>
        <tr>
            <td>
                <asp:PlaceHolder ID="plcPaging" runat="server" />
            </td>
        </tr>
    </table>

Step4 :- In code behind add the following code


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

    public partial class _Default : System.Web.UI.Page
    {
        private int RowCount
        {
            get
            {
                return (int)ViewState["RowCount"];
            }
            set
            {
                ViewState["RowCount"] = value;
            }
        }
       
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                FetchData(10, 0);    
            }
            else
            {
                plcPaging.Controls.Clear();
                CreatePagingControl();
            }                      
        }

        private void FetchData(int take, int pageSize)
        {          
            using (NorthwindDataContext dc = new NorthwindDataContext())
            {
                var query = from p in dc.Customers
                                .OrderBy(o => o.ContactName)
                                .Take(take)
                                .Skip(pageSize)
                            select new
                            {
                                ID = p.CustomerID,
                                Name = p.ContactName,
                                Count = dc.Customers.Count()
                            };
               
                PagedDataSource page = new PagedDataSource();
                page.AllowCustomPaging = true;
                page.AllowPaging = true;
                page.DataSource = query;
                page.PageSize = 10;
                Repeater1.DataSource = page;
                Repeater1.DataBind();

                if (!IsPostBack)
                {
                    RowCount = query.First().Count;
                    CreatePagingControl();
                }
            }
        }

        private void CreatePagingControl()
        {  
            for (int i = 0; i < (RowCount / 10) + 1; i++)
            {
                LinkButton lnk = new LinkButton();               
                lnk.Click += new EventHandler(lbl_Click);
                lnk.ID = "lnkPage" + (i + 1).ToString();
                lnk.Text = (i + 1).ToString();
                plcPaging.Controls.Add(lnk);
                Label spacer = new Label();
                spacer.Text = "&nbsp;";
                plcPaging.Controls.Add(spacer);
            }
        }
      
        void lbl_Click(object sender, EventArgs e)
        {
            LinkButton lnk = sender as LinkButton;
            int currentPage = int.Parse(lnk.Text);
            int take = currentPage * 10;
            int skip = currentPage == 1 ? 0 : take - 10; 
            FetchData(take, skip);
        }

}

Hope this helps

Good Luck.

Advertisements
Categories: ASP.Net, Linq Tags:

Use Regular Expression for Validation and Length Validation

March 17, 2010 Leave a comment

Hi

try this example to use Regular Expression for Validation and Length Validation

Step1 :- Open VS2005 and create a new website project

Step2 :- Add new class in App_Code folder and name it “RegExp.cs”


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

namespace Util
{
    public class RegExp
    {
        public static readonly string Url = "[a-zA-Z0-9-_\\$]+(\\.[a-zA-Z0-9-_\\$]+)?\\??[a-zA-Z0-9-_\\$]+=?[a-zA-Z0-9-_\\$]+(&[a-zA-Z0-9-_\\$]+=[a-zA-Z0-9-_\\$]+)*";
        public static readonly string Date = "(0[1-9]|[12][0-9]|3[01])[-](0[1-9]|1[012])[-]((175[7-9])|(17[6-9][0-9])|(1[8-9][0-9][0-9])|([2-9][0-9][0-9][0-9]))"; // supports dates from 1-1-1757 to 31-12-9999 for SQL Server 2000 Date Range
        public static readonly string Time = "(0[1-9]|[1][0-2])[:](0[0-9]|[1-5][0-9])[:](0[0-9]|[1-5][0-9])[ ][A|a|P|p][M|m]";
        public static readonly string Number = "[-+]?[0-9]*\\.?[0-9]*";
        public static readonly string Digit = "[0-9]*";
        public static readonly string NonNegative = "[+]?[0-9]*\\.?[0-9]*";
        public static string MaxLength(int len)
        {
            return "[\\s\\S]{0," + len.ToString() + "}";
        }
    }
}

Step3 :- Add new class also and name it “ValidationMessages.cs”


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

namespace Resource
{
    public class ValidationMessages
    {
        public static readonly string Required = "* Required";
        public static readonly string Url = "* Please enter a valid URL.<br>Valid characters are all alphanumeric characters and .?&_=-$<br> example: home.aspx?id=5&name=$my_name";
        public static readonly string Date = "* Please enter a valid date in dd-MM-yyyy format.";
        public static readonly string Time = "* Please enter a valid time in hh:mm:ss am format.";
        public static readonly string Number = "* Must be a valid number.";
        public static readonly string Digit = "* Must be a valid whole number.";
        public static readonly string NonNegative = "* Must be a non-negative number.";
        public static string MaxLength(int len)
        {
            return "* Maximum " + len.ToString() + " characters are allowed.";
        }
    }
}

Step4 :- Add new Web page

<%@ 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>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <h3>Validation Example</h3>
            <table border="1" width="50%">
                <tr>
                    <td style="width:200px">
                        <asp:Label ID="CommentLabel" runat="server" Text="Comment:"></asp:Label></td>
                    <td>
                        <asp:TextBox ID="CommentTextBox" runat="server" TextMode="MultiLine" Width="500px" />
                        <asp:RegularExpressionValidator ID="CommentValidator" runat="server" ControlToValidate="CommentTextBox"></asp:RegularExpressionValidator>
                    </td>
                </tr>
                <tr>
                    <td>
                        <asp:Label ID="DateLabel" runat="server" Text="Date:"></asp:Label></td>
                    <td>
                        <asp:TextBox ID="DateTextBox" runat="server"  Width="500px"/>
                        <asp:RegularExpressionValidator ID="DateValidator" runat="server" ControlToValidate="DateTextBox"></asp:RegularExpressionValidator>
                    </td>
                </tr>
                <tr>
                    <td>
                        <asp:Label ID="TimeLabel" runat="server" Text="Time:"></asp:Label></td>
                    <td>
                        <asp:TextBox ID="TimeTextBox" runat="server"  Width="500px"/>
                        <asp:RegularExpressionValidator ID="TimeValidator" runat="server" ControlToValidate="TimeTextBox"></asp:RegularExpressionValidator>
                    </td>
                </tr>
                <tr>
                    <td>
                        <asp:Label ID="NumberLabel" runat="server" Text="Number:"></asp:Label></td>
                    <td>
                        <asp:TextBox ID="NumberTextBox" runat="server"  Width="500px"/>
                        <asp:RegularExpressionValidator ID="NumberValidator" runat="server" ControlToValidate="NumberTextBox"></asp:RegularExpressionValidator>
                    </td>
                </tr>
                <tr>
                    <td>
                        <asp:Label ID="DigitLabel" runat="server" Text="Digit:"></asp:Label></td>
                    <td>
                        <asp:TextBox ID="DigitTextBox" runat="server"  Width="500px"/>
                        <asp:RegularExpressionValidator ID="DigitValidator" runat="server" ControlToValidate="DigitTextBox"></asp:RegularExpressionValidator>
                    </td>
                </tr>
                <tr>
                    <td>
                        <asp:Label ID="NonNegativeLabel" runat="server" Text="Non Negative:"></asp:Label></td>
                    <td>
                        <asp:TextBox ID="NonNegativeTextBox" runat="server" Width="500px" />
                        <asp:RegularExpressionValidator ID="NonNegativeValidator" runat="server" ControlToValidate="NonNegativeTextBox"></asp:RegularExpressionValidator>
                    </td>
                </tr>
                <tr>
                    <td>
                        <asp:Label ID="UrlLabel" runat="server" Text="URL"></asp:Label></td>
                    <td>
                        <asp:TextBox ID="UrlTextBox" runat="server"  Width="500px"/>
                        <asp:RegularExpressionValidator ID="UrlValidator" runat="server" ControlToValidate="UrlTextBox"></asp:RegularExpressionValidator>
                    </td>
                </tr>
            </table>
        </div>
    </form>
</body>
</html>

Step5 :- In code behind of web page add the following code


using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Util;
using Resource;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        CommentValidator.ValidationExpression = RegExp.MaxLength(50);
        CommentValidator.ErrorMessage = ValidationMessages.MaxLength(50);

        DateValidator.ValidationExpression = RegExp.Date;
        DateValidator.ErrorMessage = ValidationMessages.Date;

        TimeValidator.ValidationExpression = RegExp.Time;
        TimeValidator.ErrorMessage = ValidationMessages.Time;

        NumberValidator.ValidationExpression = RegExp.Number;
        NumberValidator.ErrorMessage = ValidationMessages.Number;

        DigitValidator.ValidationExpression = RegExp.Digit;
        DigitValidator.ErrorMessage = ValidationMessages.Digit;

        NonNegativeValidator.ValidationExpression = RegExp.NonNegative;
        NonNegativeValidator.ErrorMessage = ValidationMessages.NonNegative;

        UrlValidator.ValidationExpression = RegExp.Url;
        UrlValidator.ErrorMessage = ValidationMessages.Url;
    }
}

Hope this helps

Good Luck

Categories: ASP.Net

Use CheckBox in Repeater Control

March 17, 2010 1 comment

Hi

try this example to Use Checkboxes in a .NET Repeater control

<asp:Repeater id="customerList" runat="server">
 <ItemTemplate>
    <%# Eval("UserName") %><br />
    <%# Eval("Email") %><br />
    Send mailing list invite <asp:CheckBox id="selectUser" runat="server">
    <asp:HiddenField ID="hiddenEmail" Value ='<%#Eval("Email")%>'>
 </ItemTemplate>
 </asp:Repeater>
 <asp:Button Text="Send Email" OnClick="Send" Runat="server" />

and in code behind :-


public void Send(object sender, EventArgs e)
{
    foreach (RepeaterItem i in customerList.Items)
       {                   
          //Retrieve the state of the CheckBox
          CheckBox cb = (CheckBox)i.FindControl("selectUser");
          if (cb.Checked)
          {
               //Retrieve the value associated with that CheckBox
               HiddenField hiddenEmail = (HiddenField)i.FindControl("hiddenEmail");

               //Now we can use that value to do whatever we want
               SendWelcomeMessage(hiddenEmail.Value);
          }
       }
}

Hope this helps

Good Luck.

Categories: ASP.Net

Letter Paging Reprter with DataGrid

March 16, 2010 Leave a comment

Hi 

try this example for Letter Paging  Reprter control 

Step1 :- Open MS SQL Server2005 and attach Northwind Database 

Step2 :- Create the following Stored Procedures 

 

CREATE PROCEDURE GetCustomerLNameInitials
AS 

SELECT UPPER(SUBSTRING(CompanyName, 1, 1)) lni, COUNT(*) Num
FROM Customers
GROUP BY UPPER(SUBSTRING(CompanyName, 1, 1))
ORDER BY lni
Go

 

 

CREATE PROCEDURE GetCustomersByLNameInitial
(
   @Lni nchar(1)
)
AS 

SELECT CompanyName, Address, City, Country
FROM Customers
WHERE CompanyName LIKE @Lni + '%'
ORDER BY CompanyName
Go

 

 

CREATE PROCEDURE GetAllCutomers
AS 

SELECT CompanyName, Address, City, Country
FROM Customers
ORDER BY CompanyName
Go

Step3 :- Open VS2005 and create new website and add new class called “DataAccess.cs” 

 

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient; 

/// <summary>
/// Summary description for DataAcess
/// </summary>
public class DataAcess
{
 public DataAcess()
 {
  //
  // TODO: Add constructor logic here
  //
 } 

    public SqlDataReader GetCustomerLNameInitials()
    {
        SqlDataReader dr = null;
        // Create Instance of Connection and Command Object
        SqlConnection myConnection = new SqlConnection(ConfigurationSettings.AppSettings["connectionString"]);
        SqlCommand myCommand = new SqlCommand("GetCustomerLNameInitials", myConnection); 

        try
        {
            // Mark the Command as a SPROC
            myCommand.CommandType = CommandType.StoredProcedure;
            // Open the database connection and execute the command
            myConnection.Open();
            dr = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
            // clear Paramters
            myCommand.Parameters.Clear();
            // Return the datareader
        }
        catch
        {
            myConnection.Close();
            //throw;
        }
        return dr;
    } 

    public SqlDataReader GetCustomersByLNameInitial(string Lni)
    {
        SqlDataReader dr = null;
        // Create Instance of Connection and Command Object
        SqlConnection myConnection = new SqlConnection(ConfigurationSettings.AppSettings["connectionString"]);
        SqlCommand myCommand = new SqlCommand("GetCustomersByLNameInitial", myConnection);
        try
        {
            // Mark the Command as a SPROC
            myCommand.CommandType = CommandType.StoredProcedure;
            // Add Parameters to SPROC
            SqlParameter parameterLni = new SqlParameter("@Lni", SqlDbType.NChar, 1);
            parameterLni.Value = Lni;
            myCommand.Parameters.Add(parameterLni);
            // Open the database connection and execute the command
            myConnection.Open();
            dr = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
            // clear Paramters
            myCommand.Parameters.Clear();
            // Return the datareader
        }
        catch
        {
            myConnection.Close();
            //throw;
        }
        return dr;
    } 

    public SqlDataReader GetAllCutomers()
    {
        SqlDataReader dr = null;
        // Create Instance of Connection and Command Object
        SqlConnection myConnection = new SqlConnection(ConfigurationSettings.AppSettings["connectionString"]);
        SqlCommand myCommand = new SqlCommand("GetAllCutomers", myConnection);
        try
        {
            // Mark the Command as a SPROC
            myCommand.CommandType = CommandType.StoredProcedure;
            // Open the database connection and execute the command
            myConnection.Open();
            dr = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
            // clear Paramters
            myCommand.Parameters.Clear();
            // Return the datareader
        }
        catch
        {
            myConnection.Close();
            //throw;
        }
        return dr;
    }
}

Step4 :- Add new User control called “CustomerUserControl.ascx” and in design mode add Repeter and DataGrid Control 

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="CustomersUserControl.ascx.cs" Inherits="CustomersUserControl" %>
<table cellpadding="0" cellspacing="0" border="1">
 <tr>
  <td bgColor="#ccccff">
   <table>
    <tr>
     <td>
      <asp:Repeater ID="LetterList" runat="server" Visible="true" OnItemCommand="LetterList_ItemCommand">
       <itemtemplate>
        <asp:linkbutton id="lniLetter" runat="server" commandargument='<%# DataBinder.Eval(Container.DataItem, "Lni")%>' ToolTip='<%# "Subtotal: " + DataBinder.Eval(Container.DataItem, "Num") %>'>
         <%# DataBinder.Eval(Container.DataItem, "Lni")%>
        </asp:linkbutton>
       </itemtemplate>
      </asp:Repeater></td>
     <td><asp:LinkButton id="ShowAllUsers" runat="server" OnClick="ShowAllUsers_Click">(All)</asp:LinkButton></td>
    </tr>
   </table>
  </td>
 </tr>
 <tr>
  <td bgColor="#ccccff">
   <asp:DataGrid id="DataGrid1" HeaderStyle-backcolor="#94d6e7" Alternatingitemstyle-backcolor="#fff5ee" bordercolor="#deba84" cellspacing="2" borderstyle="None" width="100%" cellpadding="3" runat="server" BackColor="LemonChiffon">
    <AlternatingItemStyle BackColor="SeaShell"></AlternatingItemStyle>
    <HeaderStyle Font-Bold="True" BackColor="#94D6E7"></HeaderStyle>
   </asp:DataGrid>
  </td>
 </tr>
</table>

Step5 :- In code behind of user control add the following code 


using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class CustomersUserControl : System.Web.UI.UserControl
{
   
    void IniBindData()
    {
        DataAcess da = new DataAcess();
        LetterList.DataSource = da.GetCustomerLNameInitials();
        LetterList.DataBind();
        int n = LetterList.Items.Count;
        if (n > 0)
        {
            // try to find the first letter on the list
            string letter = ((LinkButton)(LetterList.Items[0].Controls[1])).CommandArgument;
            // show the Names with the first letter
            DataGrid1.DataSource = da.GetCustomersByLNameInitial(letter);
            DataGrid1.DataBind();
        }

    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            IniBindData();
        }
    }

    protected void ShowAllUsers_Click(object sender, EventArgs e)
    {
        DataAcess da = new DataAcess();
        DataGrid1.DataSource = da.GetAllCutomers();
        DataGrid1.DataBind();
    }

    protected void LetterList_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        DataAcess da = new DataAcess();
        // find the selected letter
        string letter = (string)e.CommandArgument;
        // show the name list with this initial
        DataGrid1.DataSource = da.GetCustomersByLNameInitial(letter);
        DataGrid1.DataBind();
    }
}

Step6 :- Add new web page and Drag User Control inside this page

Hope this helps

Good Luck.

Categories: ASP.Net

DropDownList with Custom Paging using Linq

March 14, 2010 2 comments

Hi

try this example to make a custom paging  with DropdownList control using Linq

Step1 :- Open VS2008 and create a new website

Step2 :- add new Linq to SQL DataContext  and name it “Northwind.dbml” and add Customer table in it

Step3 :- add new web page and Drag DropdownList control

<asp:DropDownList ID="ddl" runat="server" AutoPostBack="True"
        OnSelectedIndexChanged="ddl_SelectedIndexChanged">
    </asp:DropDownList>

Step4 :- in code behind add the following code


public partial class _Default : System.Web.UI.Page
    {
        private int Take
        {
            get
            {
                return (int)ViewState["Take"];
            }
            set
            {
                ViewState["Take"] = value;
            }
        }

        private int Skip
        {
            get
            {
                return (int)ViewState["Skip"];
            }
            set
            {
                ViewState["Skip"] = value;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                Take = 10;
                Skip = 0;
                FetchData();
            }           
        }

        private void FetchData()
        {           
            using (NorthwindDataContext dc = new NorthwindDataContext())
            {
                ddl.Items.Clear();               
                if (Skip > 0)
                {                   
                    ddl.Items.Add(new ListItem("<< Pre 10 Rows...", "Prev"));
                    ddl.AppendDataBoundItems = true;                   
                }

                var query = dc.Customers
                            .OrderBy(o => o.ContactName)
                            .Take(Take)
                            .Skip(Skip);
                ddl.DataTextField = "ContactName";
                ddl.DataSource = query.ToList();
                ddl.DataBind();

                if (ddl.Items.Count >= 10)
                {
                    ddl.Items.Add(new ListItem("Next 10 Rows >>", "Next"));   
                }
                ddl.SelectedIndex = Skip > 0 ? 1 : 0;
            }
        }

        protected void ddl_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ddl.SelectedValue == "Next")
            {
                Take += 10;
                Skip += 10;
                FetchData();
            }
            else if (ddl.SelectedValue == "Prev")
            {
                Take -= 10;
                Skip -= 10;
                FetchData();
            }
        }
    }

Hope this helps

Good Luck.

Categories: ASP.Net, Linq

Create a GridView Paging Style with Code

March 14, 2010 Leave a comment

Hi all ,

try this example to Create a GridView Paging Style with Code

to apply this example you should allow paging with Gridview then add the following code:


protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
  if (e.Row.RowType == DataControlRowType.Pager)
  {
      TableRow tRow = e.Row.Controls[0].Controls[0].Controls[0] as TableRow;
      foreach (TableCell tCell in tRow.Cells)
      {
          Control ctrl = tCell.Controls[0];              
          if (ctrl is LinkButton)
          {
              LinkButton lb = (LinkButton)ctrl;
              lb.Width = Unit.Pixel(15);
              lb.BackColor = System.Drawing.Color.DarkGray;
              lb.ForeColor = System.Drawing.Color.White;
              lb.Attributes.Add("onmouseover","this.style.backgroundColor='#4f6b72';");
              lb.Attributes.Add("onmouseout","this.style.backgroundColor='darkgray';");
          }
      }
  }
}

Hope this helps

Good Luck.

Categories: ASP.Net, CSS

Hide AJAX ModalPopup Extender using Esc key

March 5, 2010 4 comments

Hi all,

try this example to Hide AJAX ModalPopup Extender using Esc key


<%@ Page Language="C#" %>

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajaxToolkit" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="head" runat="server">
    <title>Untitled Page</title>
    <style>
    .modalBackground {
        background-color:Gray;
        filter:alpha(opacity=70);
        opacity:0.7;
    }
    </style>
</head>
<body>
    <form id="form" runat="server">
        <asp:ScriptManager ID="ScriptManager1" runat="server" />
        <script type="text/javascript">
        function pageLoad(sender, args){
            if(!args.get_isPartialLoad()){
                //  add our handler to the document's
                //  keydown event
                $addHandler(document, "keydown", onKeyDown);
            }
        }
        function onKeyDown(e){
            if(e && e.keyCode == Sys.UI.Key.esc){
                // if the key pressed is the escape key, dismiss the dialog
                $find('mdlPopupExtender').hide();
            }
        }

        </script>
        <div style="font-family:Tahoma; font-size:smaller">
            <p style="background-color:AliceBlue">
            Example page where a modal popup can only be dismissed by pressing the escape key
            </p>
            <asp:Button ID="btnShowModal" runat="server" Text="Click to show Modal" />
            <asp:Panel ID="pnlModalPanel" runat="server" Style="display: none">
                The only way to close this is to press the 'esc' key.
            </asp:Panel>
            <ajaxToolkit:ModalPopupExtender
                ID="mdlPopupExtender" runat="server"
                BackgroundCssClass="modalBackground"
                TargetControlID="btnShowModal"
                PopupControlID="pnlModalPanel"  />
        </div>
    </form>
</body>
</html>

Hope this helps

Good Luck