Archive

Archive for February, 2011

Using CustomValidator Control to Validate TextBox Length

February 28, 2011 2 comments

Hi all,

try this example to use CustomValidator Control to Validate TextBox Length

in this example i want to ensures a TextBox contains no more than 1000 words.

<asp:TextBox ID="txtText" runat="server" TextMode=" multiline" />
<asp:CustomValidator ID="cvText" ControlToValidate="txtText" runat="server" ErrorMessage="Your text is over 1000 words." OnServerValidate="cvtext_ServerValidate" ClientValidationFunction="cvText_ClientValidate" />

Using Server Side :-

protected void cvText_ServerValidate(object source, ServerValidateEventArgs args)
 {
     string[] numOfWords = args.Value.Split(new char[] { ' ' });
     args.IsValid = numOfWords.Length <= 1000;
 }

Using Client Side (Javascript) :-

function custStory_ServerValidate(source, args)
 {
     var numOfWords = args.Value.split(" ");
     args.IsValid = numOfWords.length <= 1000;
 }

Hope this helps

Good Luck.

Categories: ASP.Net, Javascript

JQuery Accordion with Data from Database

February 21, 2011 3 comments

Hi all,

try this Example to use JQuery Accordion with Data from Database :-

In this Example i will use Northwind Database and Categories Table

1) DownLoad the following JS files jquery-ui.js and jquery-1.4.4 from here

2) Open VS2008 and create a new Website project and add new Page “Dafault.aspx”

3) In Default.aspx add Repeater Control so our page will be like

<head runat="server">
    <title>Untitled Page</title>
    <link type="text/css" href="css/jquery-ui.css" rel="Stylesheet" />
    <script type="text/javascript" src="script/jquery-1.4.4.js"></script> 
    <script type="text/javascript" src="script/jquery-ui.js"></script>
    <script language="javascript" type="text/javascript">
        $(function () {
            $("#Categories").accordion();
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div id="Categories" style="width:500px;">
        <asp:Repeater ID="Repeater1" runat="server">
            <ItemTemplate>
                <h3><a href="#"><%# DataBinder.Eval(Container.DataItem, "CategoryName") %></a></h3>
                <div>
                    <p>
                        <%# DataBinder.Eval(Container.DataItem, "Description") %>
                    </p>
                </div>
            </ItemTemplate>
        </asp:Repeater>
    </div>
    </form>
</body>

and In code behind we will bind Repeater control to Data from Categories table in Database


protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Repeater1.DataSource = GetProducts();
            Repeater1.DataBind();
        }
    }

    public DataTable GetProducts()
    {
        string query = "select * from Categories";
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString);
        SqlCommand cmd = new SqlCommand(query, con);
        DataTable data = new DataTable();
        SqlDataAdapter adapter = new SqlDataAdapter(cmd);
        using (con)
        {
            con.Open();
            adapter.Fill(data);
        }
        return data;
    }

3) In Web.Config file add the Connection String to Database

<connectionStrings>
        <add name="NorthwindConnectionString" connectionString="Data Source=.;Initial Catalog=Northwind;Integrated Security=True"
            providerName="System.Data.SqlClient" />
    </connectionStrings>

Now run your website …..Hope this helps

Good Luck

Categories: ASP.Net, Jquery

How to download files from server to client using a Generic Handler

February 13, 2011 Leave a comment

Hi all,

try this example to download files from server to client using a Generic Handler :-

1) Open VS2008 and create a new Website and add new folder name it “images” and add some images with .gif extension

2) Add new Web page “Default.aspx” and Generic Handler “DownloadHandler.ashx”

3) In Default.aspx add DataList control so our page will be like this :-


<div>
      <asp:DataList ID="DataList1" runat="server" RepeatDirection="Horizontal">
        <ItemTemplate>
        <center>
            <asp:Image ID="img" ImageUrl='<%#"images/" + Container.DataItem %>' runat="server" Width="150" Height="150"/>
            <br />
            <a href='<%#string.Format("DownloadHandler.ashx?ImageName={0}",Container.DataItem)%>'>Download</a>
            </center>
        </ItemTemplate>
        </asp:DataList>
    </div>

and in code behind :-


protected void Page_Load(object sender, EventArgs e)
    {
        // Iterate through the images (only files with extension .gif) in the 'images' folder, and bind them to the

Datalist
        ArrayList al = new ArrayList();
        foreach (string file in Directory.GetFiles(Server.MapPath("images/")))
        {
            if (Path.GetExtension(file) == ".gif")
            {
                al.Add(Path.GetFileName(file));
            }
        }
        DataList1.DataSource = al;
        DataList1.DataBind();
    }

4) In Generic Handler “DownloadHandler.ashx” add this code :-


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

using System;
using System.Web;

public class DownloadHandler : IHttpHandler
{
    public void ProcessRequest (HttpContext context)
    {
        string file = "";
        // get the file name from the querystring
        if (context.Request.QueryString["ImageName"] != null)
        {
            file = context.Request.QueryString["ImageName"].ToString();
        }
        string filename = context.Server.MapPath("~/images/" + file);
        System.IO.FileInfo fileInfo = new System.IO.FileInfo(filename);
        try
        {
            if (fileInfo.Exists)
            {
                context.Response.Clear();
                context.Response.AddHeader("Content-Disposition", "inline;attachment; filename=\"" + fileInfo.Name + "\"");
                context.Response.AddHeader("Content-Length", fileInfo.Length.ToString());
                context.Response.ContentType = "application/octet-stream";
                context.Response.TransmitFile(fileInfo.FullName);
                context.Response.Flush();
            }
            else
            {
                throw new Exception("File not found");
            }
        }
        catch (Exception ex)
        {
            context.Response.ContentType = "text/plain";
            context.Response.Write(ex.Message);
        }
        finally
        {
            context.Response.End();
        }
    }

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

then run your website

Hope this helps

Good Luck

Categories: ASP.Net

Disabling an ASP.Net Validator through Javascript

February 9, 2011 Leave a comment

Hi all,

Try this example for Disabling an ASP.Net Validator through Javascript :-

You can try this javascript function to Disable and Enable ASP.Net Validation Control :


function DisableValidator()
{
  var myVal = document.getElementById('<%= myValidatorID.ClientID %>');
  ValidatorEnable(myVal, false); 
}

function EnableValidator()
{
  var myVal = document.getElementById('<%= myValidatorID.ClientID %>');
  ValidatorEnable(myVal, true); 
}

Hope this helps

Good Luck

Categories: ASP.Net, Javascript

SQL Server Function to Split Comma in Text

February 3, 2011 2 comments

Hi all

try this example to use SQL Server Function to Split Comma in Text

so Open SQL Server Management Studio and create a new SQL Query


create FUNCTION [dbo].[Fn_Split]
(
 @RowData nvarchar(max),
 @SplitOn nvarchar(5)
) 
RETURNS @RtnValue table
(
 Id int identity(1,1),
 Data nvarchar(100)
)
AS 
BEGIN
 Declare @Cnt int
 Set @Cnt = 1

 While (Charindex(@SplitOn,@RowData)>0)
 Begin
  Insert Into @RtnValue (data)
  Select Data = ltrim(rtrim(Substring(@RowData,1,Charindex(@SplitOn,@RowData)-1)))
  Set @RowData = Substring(@RowData,Charindex(@SplitOn,@RowData)+1,len(@RowData))
  Set @Cnt = @Cnt + 1
 End
 Insert Into @RtnValue (data)
 Select Data = ltrim(rtrim(@RowData))
 Return
END

and to use this function

select * from  dbo.Fn_Split ('Item 1,Item 2,Item 3,Item 4,Item 5,Item 6' )

Hope this helps

Good Luck

Categories: SQL Server