Check username availability using asp.net ajax


DATABASE TABLE:

CONNECTION STRING:

first prepare connection string in web.config file under configuration tag  as follows:

<connectionStrings>
<add name=”ConnectionString” connectionString=”Data Source=server2;Initial Catalog=Venkat123;Persist Security Info=True;User ID=sa;Password=123″/>
</connectionStrings>

WEBFORM DESIGN:

<html xmlns=”http://www.w3.org/1999/xhtml”&gt;
<head runat=”server”>
<title>Check Username availability Using Ajax</title>
<style type=”text/css”>
.waitingdiv {
background-color: #F5F8FA;
border: 1px solid #5A768E;
color: #333333;
font-size: 93%;
margin-bottom: 1em;
margin-top: 0.2em;
padding: 8px 12px;
width: 8.4em;
}
</style>

</head>
<body>
<form id=”form1″ runat=”server”>
<asp:ScriptManager ID=”scriptmanager1″ runat=”server”>
</asp:ScriptManager>
<script type=”text/javascript”>
Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(BeginRequestHandler);
function BeginRequestHandler(sender, args) {
var state = document.getElementById(‘loadingdiv’).style.display;
if (state == ‘block’) {
document.getElementById(‘loadingdiv’).style.display = ‘none’;
} else {
document.getElementById(‘loadingdiv’).style.display = ‘block’;
}
args.get_postBackElement().disabled = true;
}
</script>
<div>
<asp:UpdatePanel ID=”PnlUsrDetails” runat=”server”>
<ContentTemplate>
<table>
<tr>
<td>
UserName:
</td>
<td>
<asp:TextBox ID=”txtUsername” runat=”server” AutoPostBack=”true” ontextchanged=”txtUsername_TextChanged”/>
</td>
<td>
<div id=”checkusername” runat=”server” Visible=”false”>
<asp:Image ID=”imgstatus” runat=”server” Width=”17px” Height=”17px”/>
&nbsp;&nbsp;&nbsp;
<asp:Label ID=”lblStatus” runat=”server”></asp:Label>
</div>
</td>
</tr>
</table>
<div class=”waitingdiv” id=”loadingdiv” style=”display:none; margin-left:5.3em”>
<img src=”LoadingImage.gif” alt=”Loading” />Please wait…
</div>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>

CODE BEHIND:

protected void txtUsername_TextChanged(object sender, EventArgs e)
{
if(!string.IsNullOrEmpty(txtUsername.Text))
{
SqlConnection con = new SqlConnection(“Data Source=server2;Initial Catalog=Venkat123;Persist Security Info=True;User ID=sa;Password=123”);
con.Open();
SqlCommand cmd = new SqlCommand(“select * from Emp where UserName=@Name”, con);
cmd.Parameters.AddWithValue(“@Name”, txtUsername.Text);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
checkusername.Visible = true;
imgstatus.ImageUrl = “images.jpg”;
lblStatus.Text = “UserName Already Taken”;
System.Threading.Thread.Sleep(2000);
}
else
{
checkusername.Visible = true;
imgstatus.ImageUrl = “download.jpg”;
lblStatus.Text = “UserName Available”;
System.Threading.Thread.Sleep(2000);
}
}
else
{
checkusername.Visible = false;
}
}
}

OUTPUTRESULT:

DOWNLOAD SAMPLE CODE

How To Save and Retrive Image into/from SQL Server Database by using ASP.Net


DATABASE TABLE:

WEBFORM DESIGN:

<html xmlns="http://www.w3.org/1999/xhtml"&gt;
<head id="Head1" runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>

Image Name:<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<br />
Select Image:<asp:FileUpload ID="FileUpload1" runat="server" />
<br />
<asp:Button ID="Button1" runat="server" onclick="Button1_Click"
Text="UploadImage" />
<br />
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:BoundField HeaderText="ImageName" DataField="ImageName" />
<asp:TemplateField HeaderText="Image">
<ItemTemplate>
<asp:Image ID="Image1" runat="server" ImageUrl='<%# "ImageHandler.ashx?Id=" + Eval("Id") %>' Height="150px" Width="150px" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

</div>
</form>
</body>
</html>

CONNECTION STRING:

first prepare connection string in web.config file under configuration tag  as follows:

<connectionStrings>
        <add name="ConnectionString" connectionString=”Data Source=server2;Initial Catalog=Venkat123;Persist Security Info=True;User ID=sa;Password=123″/>”
    </connectionStrings>

CODE BEHIND:

string connectionstring = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            //getting existing data
            GetData();
        }

    }
    public void GetData()
    {
        SqlConnection con = new SqlConnection(connectionstring);
        SqlCommand cmd = new SqlCommand("select Id,ImageName from Image1", con);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataTable dt = new DataTable();
        da.Fill(dt);
        GridView1.DataSource = dt;
        GridView1.DataBind();
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        if (FileUpload1.HasFile)
        {
            //finding size of file
            int length = FileUpload1.PostedFile.ContentLength;
            //creating binary variable of above length
            byte[] imgbyte = new byte[length];
            //saving image in memory
            HttpPostedFile img = FileUpload1.PostedFile;
            //loading image into binary variable
            img.InputStream.Read(imgbyte, 0, length);
            string imgname = TextBox1.Text;
            SqlConnection con = new SqlConnection(connectionstring);
            con.Open();
            SqlCommand cmd = new SqlCommand("insert into Image1 (ImageName,ImageData) values (@imagename,@imagedata)", con);
            cmd.Parameters.Add("@imagename", SqlDbType.VarChar, 50).Value = imgname;
            cmd.Parameters.Add("@imagedata", SqlDbType.Image).Value = imgbyte;
            int count = cmd.ExecuteNonQuery();
            con.Close();
            if (count == 1)
            {
                GetData();
                TextBox1.Text = string.Empty;
            }
        }
    }

OUTPUTRESULT:

Image retrival code using handler file:

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

using System;
using System.Web;
using System.Configuration;
using System.Data.SqlClient;

public class ImageHandler : IHttpHandler {
    string connectionstring = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
    public void ProcessRequest (HttpContext context) {
        string imageid = context.Request.QueryString["Id"];
        SqlConnection con = new SqlConnection(connectionstring);
        con.Open();
        SqlCommand cmd = new SqlCommand("select ImageData from Image1 where Id=" + imageid,con);
        SqlDataReader dr = cmd.ExecuteReader();
        dr.Read();
        context.Response.BinaryWrite((Byte[])dr[0]);
        con.Close();
        context.Response.End();
    }
    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

Download Sample Code

Bind or Adding tooltip for dropdownlist items in asp.net


DataBase Table:

first create databasetable as follows:

WebForm Design:

simply add one dropDownList to webform:

<asp:DropDownList ID=”DropDownList1″ runat=”server”
ondatabound=”DropDownList1_DataBound”>
</asp:DropDownList>

Connection string:

first prepare connection string in web.config file under configuration tag  as follows:

<connectionStrings>
<add name=”ConnectionString” connectionString=”Data Source=server2;Initial Catalog=Venkat123;Persist Security Info=True;User ID=sa;Password=123″/>
</connectionStrings>

Code Behind:

string connection = ConfigurationManager.ConnectionStrings[“ConnectionString”].ToString();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{ FillDDL(); }
}
public void FillDDL()
{
SqlConnection con = new SqlConnection(connection);
SqlCommand cmd = new SqlCommand(“select UserId,UserName from Emp”,con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
DropDownList1.DataValueField = “UserId”;
DropDownList1.DataTextField = “UserName”;
DropDownList1.DataSource = dt;
DropDownList1.DataBind();
}
protected void DropDownList1_DataBound(object sender, EventArgs e)
{
DropDownList ddl = sender as DropDownList;
if (ddl != null)
{
foreach (ListItem li in ddl.Items)
{
li.Attributes[“title”] = li.Text;
}
}
}

OutputResult:

Passing variables between pages using QueryString


sometimes we need to maintain state between pages
that means we need to use values in one page in other pager for that we need to pass one page values to another page: for that we use different techniques
1.Querystring
2.sessions
3.cookies
4.viewstate
etc…
now we will learn how to pass values using query string…
first prepare form1 as follows
——————————-
take one textbox and one button
when we click on button the textbox value we need see in form2

To send One Value:

for this we need to take one text box in Form1

<asp:TextBox ID=”TextBox1″ runat=”server”></asp:TextBox>

and one button

<asp:Button ID=”Button1″ runat=”server” onclick=”Button1_Click” Text=”Send” />

write the following code in button click event

Response.Redirect(“Form2.aspx?name=”this.TextBox1.Text);

then write the following code in Form2 PageLoad event

Response.Write(Request.QueryString[“name”]);

To send Two Values:

for this we need to take two textboxes in Form1

<asp:TextBox ID=”TextBox1″ runat=”server”></asp:TextBox>

<asp:TextBox ID=”TextBox2″ runat=”server”></asp:TextBox>

and one button

<asp:Button ID=”Button1″ runat=”server” onclick=”Button1_Click” Text=”Send” />

write the following code in button click event

Response.Redirect(“Form2.aspx?name=”this.TextBox1.Text + “&lastname=” + this.TextBox2.Text);

then write the following code in Form2 PageLoad event

Response.Write(Request.QueryString[“name”]);

Response.Write(Request.QueryString[“lastname”]);

Another Way to Read values(Using for loop):

write the following code in Form2 PageLoad event

for (int i = 0; i < Request.QueryString.Count;i++ )
Response.Write(Request.QueryString[i]);

We can assign those values to textboxes in Form2 also:

Now take two textboxes in form2 and write the following code in Form2 PageLoad event

string str1 = Request[“Name”];
string str2 = Request[“lastname”];
TextBox1.Text = str1;
TextBox2.Text = str2;

Replace “space” and “&” with %20 and %26 using UrlEncode:

Observe the google Querystring it replace space by %20 and & by %26

For that we need to following

string s1 = this.TextBox1.Text.Replace(“&”, “%26”);
string s2 = this.TextBox2.Text.Replace(“&”, “%26″);
string str1 = s1.Replace(” “, “%20″);
string str2 = s2.Replace(” “, “%20”);
string url = “Form2.aspx?name=” + Server.UrlEncode(str1) + “&last=” + Server.UrlEncode(str2);
Response.Redirect(url);

————————————————————————————————-

How to restrict user to enter only digits(numbers) in textbox using javascript


<html xmlns=”http://www.w3.org/1999/xhtml”&gt;
<head runat=”server”>
<title></title>
<script type=”text/javascript”>
function allowordeny(key) {
var datakey = (key.which) ? key.which : key.keyCode;//capturing pressed key
var textboxdata = document.getElementById(“TextBox1”);//capturing textbox reference
if (datakey == 46)//allowing delete key
return true;
else if (datakey == 8)//allowing backspace key
return true;
else if ((datakey < 48 || datakey > 57))//avoiding charecters other than digits
return false;
else if (textboxdata.value.length < 10)//restricting morethan 10 digits
return true;
else {
alert(“Allow Only 10 digits”);//giving message
return false;
}
}
</script>
</head>
<body>
<form id=”form1″ runat=”server”>
<div>
<asp:TextBox ID=”TextBox1″ onkeypress=”return allowordeny(event)”
runat=”server”></asp:TextBox>
</div>
</form>
</body>
</html>