Monday, 4 March 2013

All Dotnet Codes


password strength plugin Examples
In this article i will show you collection of top 5 jQuery plugin which is responsible for calculating password strength in your registration form.

Here is my article for calculating password strength for 
Asp.Net Ajax password strength example | Password Strength indicator using Asp.net in Ajax. 

Now here is our collection:

Password strength meter

password strength

jQuery Password Strength Meter 


password strength

jQuery plugin: Password Validation


password strength

Password field with strength meter



password strength

Password Strength Checking with jQuery

password strength

Code To Insert, Update, Delete Record In Sql Server DataBase Using Asp.net (or) Perform Insert, Update,Delete Using Asp.net In C#
Now for this new article first create a new asp.net web application, and add a new page in it and add a gridview control. Here is your .aspx code.
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="BindGridView.WebForm1" %>

<!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>How To Import Excelsheet Data Into SQL Server Using Asp.Net In c#</title>
    <script language="javascript">
        function ConfirmMessage() {
            var answer = confirm("Are you sure. do you want to delete record.");
            if (answer) {
                return true;
            } else {
                return false;
            }
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
     
 
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Name :<asp:TextBox ID="TextBox1" runat="server"
 
            Width="200px"></asp:TextBox>
        <br />
        <br />
&nbsp;&nbsp;&nbsp; Address:<asp:TextBox ID="TextBox2" runat="server" Width="200px"></asp:TextBox>
        <br />
        <br />
        ContactNo :<asp:TextBox ID="TextBox3" runat="server" Width="200px"></asp:TextBox>
        <br />
        <br />
     
 
        <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Save"
            Width="93px" />
                  <asp:Button ID="Button2" runat="server"  Text="Update"
            Width="93px" onclick="Button2_Click" />
        <br />
        <br />
        <asp:Label ID="lblmessage" runat="server"
 
            style="font-weight: 700; color: #FFFFFF; background-color: #FF0000"
 
            Text=""></asp:Label>
        <br />
        <br />
        <asp:GridView runat="server" AutoGenerateColumns="False" ID="griddemo"
 
            Width="540px" onrowcommand="griddemo_RowCommand">
            <Columns>
                <asp:BoundField DataField="Name" HeaderText="Name" />
                <asp:BoundField DataField="Address" HeaderText="Address" />
                <asp:BoundField DataField="ContactNo" HeaderText="Contact No" />
                <asp:TemplateField HeaderText="Edit">
                    <ItemTemplate>
                        <a href="WebForm1.aspx?ID=<%#Eval("Id") %>">Update</a>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Delete">
                    <ItemTemplate>
                        <asp:LinkButton ID="Delete" CommandName="Delete" runat="server" OnClientClick="javascript:return ConfirmMessage();">Delete</asp:LinkButton>
                        <asp:Label runat="server" Text=`<%#Eval("Id") %>` ID="lblid"></asp:Label>
                    </ItemTemplate>
                   
 
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
    </div>   
 
    </form>
</body>
</html>


Now add the below code in your .cs page.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.IO;
using System.Data.OleDb;

namespace BindGridView
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        SqlConnection objcon = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ToString());
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.QueryString["ID"] == null)
            {
                Button1.Visible = true;
                Button2.Visible = false;
            }
            else
            {
                Button2.Visible = true;
                Button1.Visible = false;
                if (!IsPostBack)
                {
                    GetDataById(Request.QueryString["ID"].ToString());
                }
            }
            if (!IsPostBack)
            {
                BindGrid();
            }
        }
        protected void Button1_Click(object sender, EventArgs e)
        {
            try
            {
                string query = "Insert into student([Name],[Address],[ContactNo]) values(`" + TextBox1.Text + "`,`" + TextBox2.Text + "`,`" + TextBox3.Text + "`);SELECT @@IDENTITY as Pkvalue;";
                SqlDataAdapter objda = new SqlDataAdapter(query, objcon);
                objcon.Open();
                objda.SelectCommand.ExecuteNonQuery();
                objcon.Close();
                lblmessage.Text = "Data saved successfully.";
                BindGrid();
            }
            catch
            {
                lblmessage.Text = "Error while saving the record.";
            }
        }

        protected void Button2_Click(object sender, EventArgs e)
        {
            try
            {
                DataTable objdt = new DataTable();
                string query = "update student set [Name]=`" + TextBox1.Text + "`,[Address]=`" + TextBox2.Text + "`,[ContactNo]=`" + TextBox3.Text + "` where Id=" + Request.QueryString["ID"].ToString() + ";";
                SqlDataAdapter objda = new SqlDataAdapter(query, objcon);
                objcon.Open();
                objda.SelectCommand.ExecuteNonQuery();
                objcon.Close();
                lblmessage.Text = "Data updated successfully.";
                BindGrid();
            }
            catch
            {
                lblmessage.Text = "Error while saving the record.";
            }
        }
        private void GetDataById(string id)
        {
            try
            {
                DataTable objdt = new DataTable();
                string query = "select * from student where Id=`" + id + "`;";
                SqlDataAdapter objda = new SqlDataAdapter(query, objcon);
                objcon.Open();
                objda.Fill(objdt);
                objcon.Close();
                if (objdt.Rows.Count > 0)
                {
                    TextBox1.Text = objdt.Rows[0]["Name"].ToString();
                    TextBox2.Text = objdt.Rows[0]["Address"].ToString();
                    TextBox3.Text = objdt.Rows[0]["ContactNo"].ToString();
                }
            }
            catch
            {
                // lblmessage.Text = "Error while getting the record.";
            }
        }
        private void BindGrid()
        {
            try
            {
                DataTable objdt = new DataTable();
                string query = "select * from student;";
                SqlDataAdapter objda = new SqlDataAdapter(query, objcon);
                objcon.Open();
                objda.Fill(objdt);
                objcon.Close();
                if (objdt.Rows.Count > 0)
                {
                    griddemo.DataSource = objdt;
                    griddemo.DataBind();
                }
            }
            catch
            {
                lblmessage.Text = "Error while getting the record.";
            }
        }
        protected void DeleteRecord(string DeleteID)
        {
            try
            {
                DataTable objdt = new DataTable();
                string query = "delete from student where Id=`" + DeleteID + "`";
                SqlDataAdapter objda = new SqlDataAdapter(query, objcon);
                objcon.Open();
                objda.SelectCommand.ExecuteNonQuery();
                objcon.Close();
                Response.Redirect("WebForm1.aspx");
            }
            catch
            {
                lblmessage.Text = "Error while saving the record.";
            }
        }

        protected void griddemo_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName.Equals("Delete"))
            {
                GridViewRow row = (GridViewRow)((LinkButton)e.CommandSource).NamingContainer;
                Label lblid = (Label)griddemo.Rows[row.RowIndex].FindControl("lblid");
                DeleteRecord(lblid.Text);
            }
        }

    }
}


Now run the application.

manage data

INSERT

Insert record

After saving the record.

Insert record

UPDATE

UPDATE RECORD

DELETE

DELTE RECORD

PRESS OK

delete record

Thanks...


__________________________

DOWNLOAD
__________________________

Captcha Code In Asp.Net Using C#
So for this current article first you needed to create a new asp.net application. in this add two aspx file first default.aspx and second one is captchacode.aspx .
In your
 captchacode.aspx add the below code .  This code is used for making the captcha code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Text;
using System.Drawing.Imaging;
using System.IO;
namespace Cappachacode
{
    public partial class captcha : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Random r = new Random();
            //Captcha no
            string captchacode = r.Next(10000, 99999).ToString();
            //Storing captcha no in sessin to validate
            Session["captchacode"] = captchacode;
            Color FontColor = Color.Blue;
            Color BackColor = Color.White;
            //Define fone name
            String FontName = "Arial";
            //Define the font size
            int FontSize = 40;
            //define captcha height
 
            int Height = 60;
            //Define captcha width
            int Width = 174;
            //Define bit map image width and height
            Bitmap bitmap = new Bitmap(Width, Height);
            Graphics graphics = Graphics.FromImage(bitmap);
            Color color = Color.Gray; ;
            Font font = new Font(FontName, FontSize);
            //define where the text will be displayed in the specified area of the image
            PointF point = new PointF(5.0F, 5.0F);
            //Assigning fone color
            SolidBrush BrushForeColor = new SolidBrush(FontColor);
            //Define captcha background color
            SolidBrush BrushBackColor = new SolidBrush(BackColor);
            Pen BorderPen = new Pen(color);
            Rectangle displayRectangle = new Rectangle(new Point(0, 0), new Size(Width - 1, Height - 1));
            graphics.FillRectangle(BrushBackColor, displayRectangle);
            graphics.DrawRectangle(BorderPen, displayRectangle);

            //Define string format
 
            StringFormat format1 = new StringFormat(StringFormatFlags.NoClip);
            StringFormat format2 = new StringFormat(format1);
            //Draw text string using the text format
            graphics.DrawString(captchacode, font, Brushes.Red, (RectangleF)displayRectangle, format2);
            Response.ContentType = "image/jpeg";
            //Defining bitmap type
            bitmap.Save(Response.OutputStream, ImageFormat.Jpeg);
        }
    }
}

Here i have stored the random no in session. this session value we will validate with the user entered value.
your .aspx page will look as shown below.
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="captcha.aspx.cs" Inherits="Cappachacode.captcha" %>


Now come your default.aspx page . in this page add a text box and a button anda image control.
In this image url will be the the path of the image.
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="Cappachacode.WebForm1" %>

<!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">
    <asp:Label ID="lblmessage" runat="server"
 
        style="color: #FFFFFF; font-weight: 700; background-color: #FF0000"></asp:Label>
    <br />
    <br />
    <asp:TextBox ID="TextBox1" runat="server" Width="200px"></asp:TextBox>
&nbsp;
    <asp:Button ID="Button1" runat="server" onclick="Button1_Click"
 
        Text="Validate Captcha" />
    <br />
    <br />
   
 <asp:Image ID="Image1" runat="server" Height="40px" ImageUrl="captcha.aspx" 
        Width="149px" />

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

Now generate the button click event of the button and add the below code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Cappachacode
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            string captchacode=Session["captchacode"].ToString();
            if (captchacode == TextBox1.Text)
            {
                Response.Redirect("WebForm2.aspx");
            }
            else
            {
                lblmessage.Text = "You have entered WRONG captcha code.";
            }
        }

    }
}


now run the application.

captcha code

Now click the button

captcha code

Now again run the page and enter wrong code.

captcha code

_____________________________________

DOWNLOAD
_____________________________________




Simple Signup Form in Asp.net Using C#
First you needed to create the table for registration in your sql server. here is he code for you sql table
/****** Object:  Table [dbo].[UserRegistration]    Script Date: 01/16/2013 23:47:49 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[UserRegistration](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [UserId] [varchar](50) NULL,
    [Password] [varchar](50) NULL,
    [Name] [varchar](50) NULL,
    [Address] [varchar](50) NULL,
    [ContactNo] [int] NULL,
 CONSTRAINT [PK_UserRegistration] PRIMARY KEY CLUSTERED
 
(
    [Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

SET ANSI_PADDING OFF
GO

In design mode your table will look as shown below.

sql table

you will not get any data in your table.

sql table

Now you create a new asp.net application. add a .aspx page in it.
Now in this page add the below html code by crating the click event of the button,
<p><h2>
        <strong>Simple Sinup Form in Asp.net Using C#&nbsp;&nbsp;&nbsp;</h2></p>
    <p>
        &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
 
        User Id :<asp:TextBox ID="txtuserid" runat="server" Width="150px"></asp:TextBox>
        <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
 
            CssClass="style1" ErrorMessage="Please enter user id"
 
            ControlToValidate="txtuserid" Display="Dynamic"></asp:RequiredFieldValidator>
    </p>
    <p>
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
 
        Password :<asp:TextBox ID="txtpassword"
 
            runat="server" Width="150px" TextMode="Password"></asp:TextBox>
        <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server"
 
            CssClass="style1" ErrorMessage="Please enter password"
 
            ControlToValidate="txtpassword" Display="Dynamic"></asp:RequiredFieldValidator>
    </p>
    <p>
        Con. Password :<asp:TextBox ID="txtconformpassword" runat="server" Width="150px"
 
            TextMode="Password"></asp:TextBox>
        <asp:RequiredFieldValidator ID="RequiredFieldValidator5" runat="server"
 
            CssClass="style1" ErrorMessage="Please enter confirm password."
 
            ControlToValidate="txtconformpassword" Display="Dynamic"></asp:RequiredFieldValidator>
        <asp:CompareValidator ID="CompareValidator1" runat="server"
 
            ControlToCompare="txtpassword" ControlToValidate="txtconformpassword"
 
            Display="Dynamic" ErrorMessage="Password and confirm password are not same."
 
            style="color: #FF0000"></asp:CompareValidator>
    </p>
    <p>
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
         Name :<asp:TextBox ID="txtname" runat="server" Width="150px"></asp:TextBox>
        <asp:RequiredFieldValidator ID="RequiredFieldValidator6" runat="server"
 
            CssClass="style1" ErrorMessage="Please enter name."
 
            ControlToValidate="txtname" Display="Dynamic"></asp:RequiredFieldValidator>
    </p>
    <p>
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
 
        Address:<asp:TextBox ID="txtaddress" runat="server" Width="150px"></asp:TextBox>
    </p>
    <p>
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        Contact No:<asp:TextBox ID="txtcontactno" runat="server" Width="150px"></asp:TextBox>
    </p>
    <p>
        <asp:Label ID="lblmessage" runat="server" Style="color: #FFFFFF; background-color: #FF0000"
            Text=""></asp:Label>
    </p>
    <p>
        <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Save" Width="103px" />
    </p>


In this i have added validation controls. As you run the page your page will look as shown below.

REGISTRATION FOR IN ASP.NET

Now click on button validation will occur. it will not allow you to make the post.

REGISTRATION FOR IN ASP.NET

In your web.config add the below connection string setting.
<connectionStrings>
    <add name="ConnectionString"
        connectionString="data source=SQLEXPRESS;database=DemoArticles;uid=so;pwd=123;"
        providerName="System.Data.SqlClient" />
  </connectionStrings>

Now come to you .cs page and add the below code on button click event.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;

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

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            try
            {
                SqlConnection objcon = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ToString());
                DataTable objdatatable = new DataTable();
                string validationquery = "select * from UserRegistration where UserId=`" + txtuserid.Text + "`";
                SqlDataAdapter objdavalidate = new SqlDataAdapter(validationquery, objcon);
                objdavalidate.SelectCommand.CommandType = CommandType.Text;
                objdavalidate.Fill(objdatatable);
                if (objdatatable.Rows.Count > 0)
                {
                    lblmessage.Text = "User Id already exists.";
                    txtuserid.Text = "";
                }
                else
                {
                    try
                    {
                        string insertquery = "insert into UserRegistration(UserId,Password,Name,Address,ContactNo) values(`" + txtuserid.Text + "`,`" + txtpassword.Text + "`,`" + txtname.Text + "`,`" + txtaddress.Text + "`,`" + txtcontactno.Text + "`)";
                        SqlDataAdapter objda = new SqlDataAdapter(insertquery, objcon);
                        objda.SelectCommand.CommandType = CommandType.Text;
                        objcon.Open();
                        objda.SelectCommand.ExecuteNonQuery();
                        objcon.Close();
                        lblmessage.Text = "Data saved successfully.";
                    }
                    catch
                    {
                        lblmessage.Text = "Error while creating user id.";
                    }
                }
            }
            catch
            {
                lblmessage.Text = "Error while saving the record.";
            }
        }
    }
}


In above code first i have validated if user id already exist or not if not then save the user record. other wise it will throw the error message.

Now we have done our coding run the page. run the page after adding all details click on save button;

REGISTRATION FOR IN ASP.NET

if your password and confirm password will different then you will get the below error message.

REGISTRATION FOR IN ASP.NET

Now in you .cs file first we will check weather user id exist in system or not if not then you will not get any record.

REGISTRATION FOR IN ASP.NET

Now data will save and you will be able to see it in your sql table.

REGISTRATION FOR IN ASP.NET
now again try to register with same user id. you will get the error message that user id will appear. here i have shown that if user already exists on that case you will record in your collection.

REGISTRATION FOR IN ASP.NET

now final o/p

REGISTRATION FOR IN ASP.NET

This will prevent to create duplicate user id in your system.

_______________________________

DOWNLOAD
_______________________________





How To Pass Data Between Two Pages In Asp.net
In this article i will show you different processes to pass data between two pages in asp.net.

So for this article first you needed to create a n asp.net web application.  So the different precesses are as follows. You can perform the operation on button click event.

suppose you have a label control and you are siaplaying the value on it.

QUERYSTRING
For passing the value.
Response.Redirect("QueryStringPage.aspx?Data=" + YouValue);

For retriving.


Label1.Text=Request.QueryString["Data"].ToString();

SESSION STATE

For passing the value
Session["Data"] = YourValue;
Response.Redirect("SessionStatePage.aspx");
For retriving

Label1.Text=Session["Data"].ToString();

 
BY PUBLIC PROPERTY

For this define a public property
public string DataToSend
{
get
{
return yourvalue;
}
}
Now on button click redirect to other page.

Server.Transfer("PublicPropertiesPage.aspx");

For accessing the value

Lable1.Text=PreviousPage.DataToSend;


CONTEROL INFO:

Suppose you have a textbox in the page
<asp:TextBox ID="DataToSendTextBox" runat="server" Text="Dotnetpools.com"></asp:TextBox><br />

now on button click put the code

Server.Transfer("ControlInfoPage.aspx");
now on other page accessing the value

var textbox = PreviousPage.FindControl("DataToSendTextbox") as TextBox;
if (textbox != null)
{
   Label.Text = textbox.Text;
}




 
How To Get Newly Inserted Record In Sql Server DataBase Using ADO.Net In Asp.Net
Some of my newly created article in asp.net articles are as follows.
Redirection To Login page After Session Time Out In Asp.Net ,Asp.Net Pass Multiple Parameters in Query String or URL, Jquery Code To Get Browser Name And Version In Asp.Net,Binding Dropdownlist Control To An xml File Using C# in Asp.Net ,Asp.Net GridView Image Bind

So for this article first you needed to create an asp.net application. In this article add a new page and then add some textbox and button control. After adding the control your html will look as shown below.
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="BindGridView.WebForm1" %>

<!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>How To Import Excelsheet Data Into SQL Server Using Asp.Net In c#</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
     
 
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Name :<asp:TextBox ID="TextBox1" runat="server"
 
            Width="200px"></asp:TextBox>
        <br />
        <br />
&nbsp;&nbsp;&nbsp; Address:<asp:TextBox ID="TextBox2" runat="server" Width="200px"></asp:TextBox>
        <br />
        <br />
        ContactNo :<asp:TextBox ID="TextBox3" runat="server" Width="200px"></asp:TextBox>
        <br />
        <br />
     
 
        <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Save"
            Width="93px" />
        <br />
        <br />
        <asp:Label ID="lblmessage" runat="server"
 
            style="font-weight: 700; color: #FFFFFF; background-color: #FF0000"
 
            Text=""></asp:Label>
    </div>
    </form>
</body>
</html>

Now add the below code on button click event of the button.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.IO;
using System.Data.OleDb;

namespace BindGridView
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }
        protected void Button1_Click(object sender, EventArgs e)
        {
            SqlConnection objcon = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ToString());
            try
            {
               
 DataTable objdt = new DataTable();
                string query = "Insert into student([Name],[Address],[ContactNo]) values(`" + TextBox1.Text + "`,`" + TextBox2.Text + "`,`" + TextBox3.Text + "`);SELECT @@IDENTITY as Pkvalue;";
                SqlDataAdapter objda = new SqlDataAdapter(query, objcon);
                objcon.Open();
                objda.Fill(objdt);
                objcon.Close();
                lblmessage.Text = "Your newly saved record Id is :" + objdt.Rows[0]["Pkvalue"].ToString();
            }
            catch
            {
                lblmessage.Text = "Error while saving the record.";
            }
        }
    }
}

In this after insert query i have added
 SELECT @@IDENTITY as Pkvalue; this will return the newly inserted column value.
Here i have created datatable and stored the record in datable.
 
Now open your sql server.

id key

Here we have 6 record in out table. Now run the page and add the record.

insert form

now click on save here after saving the data. Here is the datatable record  which i am displaying of datatable.

datatable

Now press F5 to complete the precess. Now here is the new records in the sql table.

primery key

and here is the final output .

primery key

Redirection To Login page After Session Time Out In Asp.Net
So on the button click add the below code. in this code i am assigning value to session .

protected void btnGenerate_Click(object sender, EventArgs e)
{
Session["SessionID"]=txtSession.Text;
}

Now on second button add the below code.
protected void btnCheck_Click(object sender, EventArgs e)
{
if (Session["SessionID"] != null)
{
txtSession.Text = Session["SessionID"].ToString();
}
else
{
Response.Redirect("Default2.aspx");
}
}

In above code i have checked if session value is null then redirect to the second page . In case of login page you can check the session value on page load.

Asp.Net Pass Multiple Parameters in Query String or URL
Now on page one add an asp.net button control and put the code on it`s click event.
<!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:button runat="server" text="Clic To Pass Request Quesry String Value"
id="btnclick" onclick="btnclick_Click" />
</div>
</form>
</body>
</html>

C#:
protected void btnclick_Click(object sender, EventArgs e)
{
Response.Redirect("Page2.aspx?value1=100000&value2=20000");
}

In aboce c# code i have passed two value value1 and value2 as a request querystring and i have assigh value to it.

Now come to your page2.aspx. In this page add two lable . This label is used for displaying the request quesrystring value.

<body>
<form id="form1" runat="server">
<div>
<h2>Result of request querystring</h2><br />
Value 1 :<asp:Label ID="Label1" runat="server" Text=""></asp:Label><br />
Value 3 : <asp:Label ID="Label2" runat="server" Text=""></asp:Label>
</div>
</form>
</body>

Now open .cs page for adding hte coce.

protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["value1"] != null)
{
Label1.Text = Request.QueryString["value1"].ToString();
}
if (Request.QueryString["value2"] != null)
{
Label2.Text = Request.QueryString["value2"].ToString();
}
}

In above code i have checked that whether the querystring is null or not if not then assign the value to label. If we will not put any check and some how name got changed on that case we will get
 object refrance not set to an instance an object.

Now run the code you will get below screen
http://www.dotnetpools.com/images/ArticleImages/IMG-4557514491000000-724.png

Now click on button. But before that put a creak point on page load of page2.cs.
http://www.dotnetpools.com/images/ArticleImages/IMG-9743787291000000-619.png

In above it`s showing the value of request querysting .
http://www.dotnetpools.com/images/ArticleImages/IMG-7068184121000000-450.png

_______________________________

________________________________



How to write stored procedure with output parameter in sql server
In this article i will show you how you can create a new stored procedure in sql server . In this you will also learn how to create stored procedure with output parameter.

When we write stored procedure in  that case in some situations we need some return some value depending upon operation.

so here is the stored procedure.

-- =============================================
-- Author:        Vinay Singh
-- Description:    In this we will check for duplicate student name
-- =============================================
CREATE PROCEDURE SP_Student
@Name varchar(50),
@Address varchar(50),
@Marks varchar(50),
@ContactNo varchar(50),
@ReturnMessage varchar(50) OUT
AS
BEGIN
SET NOCOUNT ON;
    IF NOT EXISTS(SELECT * FROM Student WHERE Name=@Name)
    Begin
        INSERT INTO [DemoArticles].[dbo].[Student]
           ([Name]
           ,[Address]
           ,[Marks]
           ,[ContactNo])
     VALUES
           (@Name,
           @Address,
           @Marks,
           @ContactNo)
           --This message will return if data get saved successfully.
           SET @ReturnMessage=@Name+`- Student data saved successfully`
          
 
    End
    Else
    Begin
        SET @ReturnMessage=@Name+` Student Name Already Exists`
    End
END
GO

This will return "successful message with student name " if data saved successfully, else it will return error message for duplicate name in data base. 

How To Use RequiredFieldValidator control with DropDownList control For Validation
In this article i will show you how you can use requiredfieldvalidator control with dropdownList control for validation.

some of my previous articles are as follows.


So for this article here is the code
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm7.aspx.cs" Inherits="WebApplication1.WebForm7" %>

<!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:DropDownList ID="DropDownList1" runat="server" Width="200px">
    </asp:DropDownList><asp:RequiredFieldValidator ID="RequiredFieldValidator1" ControlToValidate="DropDownList1" runat="server" ErrorMessage="Please select item."></asp:RequiredFieldValidator>
    </div>
    <br />
    <asp:button runat="server" text="Submit" onclick="Unnamed1_Click" />
    <br />
    <asp:Label ID="Label1" runat="server" style="color: #FF3300" Text=""></asp:Label>
    </form>
</body>
</html>
Now in your .cs page add the below code .
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 WebForm7 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                DropDownList1.Items.Add(new ListItem("Select Item", ""));
                DropDownList1.Items.Add(new ListItem("Item 1", "1"));
                DropDownList1.Items.Add(new ListItem("Item 2", "2"));
                DropDownList1.Items.Add(new ListItem("Item 3", "3"));
                DropDownList1.Items.Add(new ListItem("Item 4", "4"));
                DropDownList1.Items.Add(new ListItem("Item 5", "5"));
            }
        }

        protected void Unnamed1_Click(object sender, EventArgs e)
        {
            Label1.Text = "Page post take place.";
        }
    }
}
Now run the application for checking output.

ddl

ddl

ddl
Better Way To Integrate Facebook Like Button In You Asp.net Website In this article i will show you how you can integrate the facebook like button in your asp.net or mvc3 application. 

So for this go to your login to your
 facebook account not in footer select developer.

facebook

Now click on developer link. In opened window select the web option.

facebook


Now in the open window select the
 Likebutton

facebook

Now a from will open in this enter the details and click on get code button to get the api code.

facebook

In code window select the i frame

facebook

Now copy the code and past it to your application.
  <iframe src="//www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.dotnetpools.com%2F&amp;send=false&amp;layout=standard&amp;width=450&amp;show_faces=true&amp;font&amp;colorscheme=light&amp;action=like&amp;height=80" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:450px; height:80px;" allowTransparency="true"></iframe>


Your like button will looks as shown below.


facebook
Fileupload Control In Asp.net
In this article i will show you how to upload a file using fileuploadcontrol using C# in asp.net. In this article i will show you some of the important functionality which we can perform wile uploading the file.
For uploading file first create a new web project. Add a new aspx page. After adding aspx page add a fileuploadcontrol, Button and a Label. After adding you html code of page will look as shown below:

<form id="form1" runat="server">
    <div>
        <h2>
            Fileupload control in asp.net</h2>
    </div>
    <div>
        <asp:FileUpload ID="FileUpload1" runat="server" />
    </div>
    <div>
        <asp:Button ID="btnupload" runat="server" Text="Upload Your File"
 
            onclick="btnupload_Click" />
    </div>
    <div>
        <asp:Label ID="lblmessage" runat="server" Style="color: #FF0000; font-weight: 700"
            Text=""></asp:Label>
    </div>
    </form>
Now create a new folder by "image".

http://www.dotnetpools.com/images/ArticleImages/IMG-2874672851000000-914.png


Now by clicking on button control generate the click event of the button control. As you click on button on your .cs page you will get code as shows below

 protected void btnupload_Click(object sender, EventArgs e)
        {
         
 
        }

Now we will write code to upload file:
 
protected void btnupload_Click(object sender, EventArgs e)
        {
            if (FileUpload1.HasFile)
            {
                string fileName = System.IO.Path.GetFileName(FileUpload1.FileName);
                FileUpload1.SaveAs(Server.MapPath("~/images/" + fileName));
                lblmessage.Text = "File uploaded successfully.";
            }
            else
            {
                lblmessage.Text = "Please select file.";
            }
        }
In above code in first line we have checked weather user have selected any file or not if user have not selected any file then he will get the error message that "Please select file".
Now if user select file in this first we will get the file name. After that we will file save the file name in image folder. In this we are not doing any special validation like file size,file extension, save file by user specified file name.
Now we will run the page . After running page we will get following screen:

http://www.dotnetpools.com/images/ArticleImages/IMG-5871821391000000-959.png

Now without selecting click on button you will get error message.

http://www.dotnetpools.com/images/ArticleImages/IMG-5104193361000000-981.png

Now select a file and click on button for uploading the file.

http://www.dotnetpools.com/images/ArticleImages/IMG-7071975691000000-376.png

After successful upload following screen will come.

http://www.dotnetpools.com/images/ArticleImages/IMG-4334078751000000-267.png

Now open your image folder which you have created. You will get the uploaded image.
http://www.dotnetpools.com/images/ArticleImages/IMG-1977203251000000-342.png
Binding GridView Using C# in Asp.Net
In this article i will show you how to bind a gridview using C# in asp.net. The code which i am going to show you is the simplest one which used for binding the gridview.

So here we go.
First you need to create a project . After creating a project add a blank page. In this blank page add a grid view control from your toolbox as shown below:



Now open your sql server and create a table in your data base . Here i have create a table named area for demo.

http://dotnetpools.com/images/ArticleImages/IMG-9531015461000000-678.png
now save you table and minimize your sql server window.

Now again come to Visual studio. Open your webpage which you have created earlier, and at right top corner of you grid select the tip as shown below:

http://dotnetpools.com/images/ArticleImages/IMG-7657851431000000-88.png

Now select edit template, a window will open 

http://dotnetpools.com/images/ArticleImages/IMG-6046144721000000-931.png

Now select bound field and click on add define HeaderText and DataFid. In header text we will add the header text for the fiend. In DataField we will add the table field Name which we are going to find.

after adding all the fields click on ok button. After click on ok button your grid will look as shown below:

http://dotnetpools.com/images/ArticleImages/IMG-6127518321000000-933.png

Now for removing auto generated column we will select property window for grid view, and select autographed column false  as shown below:

http://dotnetpools.com/images/ArticleImages/IMG-7567794141000000-561.png

After doing all this go the your source code view.you will get your html page code:

 
<asp:GridView runat="server" AutoGenerateColumns="False" ID="griddemo">
            <Columns>
                <asp:BoundField DataField="AreaID" HeaderText="Area ID" />
                <asp:BoundField DataField="AreaName" HeaderText="Area Name" />
                <asp:CheckBoxField DataField="IsDeleted" HeaderText="Is Deleted" />
            </Columns>
        </asp:GridView>

Now open you web.config file and define connection string as shown below:

 
<connectionStrings>
    <add name="ConnectionString1" connectionString="Data Source=Servername;Initial Catalog=DBname;udi=userid;pwd=password;Integrated Security=True"
      providerName="System.Data.SqlClient" />
  </connectionStrings>

Now open your web page and open your .cs page. and add the following code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
namespace DataGridBinding
{
    public partial class About : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            DataTable dt = new DataTable();
            SqlConnection objcon = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString1"].ToString());
            SqlDataAdapter objda = new SqlDataAdapter("select * from AreaTable", objcon);
            objda.Fill(dt);
            if (dt.Rows.Count > 0)
            {
                griddemo.DataSource = dt;
                griddemo.DataBind();
            }
        }
    }
}

Above code description is as follows:
1. First we have define datatable.
2. Now define connectionstring 
3. Define sqldataadaptor with sql query
4. Now fill data table
5. Check weather we have got any record from data base or not. if count is greater the 0 then we will bind the grid.

So here is the final output:

http://dotnetpools.com/images/ArticleImages/IMG-9377409671000000-299.png
In this article i will show you how to bind a gridview which contain image using C# in asp.net. The code which i am going to show you is the simplest one which used for binding the gridview image.

So here we go.
First you need to create a project . After creating a project add a blank page. In this blank page add a grid view control from your toolbox as shown below:

http://dotnetpools.com/images/ArticleImages/IMG-624934811000000-818.png

Now open your sql server and create a table in your data base . Here i have create a table named area for demo.

http://www.dotnetpools.com/images/ArticleImages/IMG-6309755801000000-59.png
now save you table and minimize your sql server window.

Now again come to Visual studio. Open your webpage which you have created earlier, and at right top corner of you grid select the tip as shown below:

http://dotnetpools.com/images/ArticleImages/IMG-7657851431000000-88.png

Now select edit template, a window will open
 
http://www.dotnetpools.com/images/ArticleImages/IMG-528759781000000-658.png
Now select bound field and click on add define
 HeaderText and DataFid. In header text we will add the header text for the fiend. In DataField we will add the table field Name which we are going to find.
For image we will add
 TempleteField.

after adding all the fields click on ok button. After click on ok button your grid will look as shown below:

http://www.dotnetpools.com/images/ArticleImages/IMG-2632168601000000-238.png

Now for removing auto generated column we will select property window for grid view, and select
 autographed column false  as shown below:

http://dotnetpools.com/images/ArticleImages/IMG-7567794141000000-561.png

After this we will add image in image template.

http://www.dotnetpools.com/images/ArticleImages/IMG-1576313021000000-980.png

For binding image in grid view we have to add by using
 Eval("ImageUrl"). In beow screen show we have shown how to bind template using image.
http://www.dotnetpools.com/images/ArticleImages/IMG-1057759601000000-420.png

After doing all this go the your source code view.you will get your html page code:

 
  <asp:GridView runat="server" AutoGenerateColumns="False" ID="griddemo">
            <Columns>
                <asp:BoundField DataField="AreaID" HeaderText="Area ID" />
                <asp:BoundField DataField="AreaName" HeaderText="Area Name" />
                <asp:TemplateField HeaderText="Image">
                    <ItemTemplate>
                        <asp:Image ID="Image1" runat="server" Height="88px"
 
                            ImageUrl=`<%# Eval("ImageUrl") %>` Width="97px" />

                    </ItemTemplate>
                </asp:TemplateField>
                <asp:CheckBoxField DataField="IsDeleted" HeaderText="Is Deleted" />
            </Columns>
        </asp:GridView>

Now open you web.config file and define connection string as shown below:

 
<connectionStrings>
    <add name="ConnectionString1" connectionString="Data Source=Servername;Initial Catalog=DBname;udi=userid;pwd=password;Integrated Security=True"
      providerName="System.Data.SqlClient" />
  </connectionStrings>

Now open your web page and open your .cs page. and add the following code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
namespace DataGridBinding
{
    public partial class About : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            DataTable dt = new DataTable();
            SqlConnection objcon = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString1"].ToString());
            SqlDataAdapter objda = new SqlDataAdapter("select * from AreaTable", objcon);
            objda.Fill(dt);
            if (dt.Rows.Count > 0)
            {
                griddemo.DataSource = dt;
                griddemo.DataBind();
            }
        }
    }
}

Above code description is as follows:
1. First we have define datatable.
2. Now define connectionstring
 
3. Define sqldataadaptor with sql query
4. Now fill data table
5. Check weather we have got any record from data base or not. if count is greater the 0 then we will bind the grid.

So here is the final output:

http://www.dotnetpools.com/images/ArticleImages/IMG-1751673571000000-576.png


·      
o   
o  ▼  September (20)
o  ▼  October (8)
o  ▼  November (7)
·     ▼  2013 (4)
o  ▼  February (3)
o  ▼  March (1)




GridView Control in ASP.NET: Part 1

RELATED ARTICLES


No comments:

Post a Comment