Thursday 31 May 2012

Using Gridview Rowcommand Edit, Delete and Update..........

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript">
          function ConfirmOnDelete()
        {
          if (confirm("Are you sure to delete?")==true)
            return true;
          else
            return false;
        }
</script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <table style="width:100%; height:383px;" cellspacing="0" cellpadding="0">
       <tr>
        <td style="width:200px">Emp Id</td>
          <asp:TextBox ID="TextBox1" runat="server" Height="21px" Width="171px"></asp:TextBox>
        </td>
        </tr>
    <tr>
    <td style="width:200px"></td>
    <td style="width:200px">Emp Name</td>
    <td style="width:200px">
        <asp:TextBox ID="TextBox2" runat="server" Height="21px" Width="171px"></asp:TextBox>
        </td>
       <tr>
       <td style="width:200px">Emp Phone</td>
    <td style="width:200px">
        <asp:TextBox ID="TextBox3" runat="server" Height="21px" Width="171px"></asp:TextBox>
        </td>
        </tr>
    <tr>
       <td style="width:200px">
        <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Insert"
            ToolTip="Insert" />
        <asp:Button ID="btn_cancle" runat="server" onclick="btn_cancle_Click"
            Text="Cancle" ToolTip="Cancle" Visible="False" />
        <asp:Button ID="btn_clear" runat="server" onclick="btn_clear_Click"
            Text="Clear" />
        </td>
    <td style="width:200px">
        <asp:Button ID="Searchbtn" runat="server" onclick="Searchbtn_Click"
            Text="Search" />
        </td>
       </tr>
    <tr>
       <td style="width:200px">
        <asp:Button ID="Button2" runat="server" Text="Button" />
        </td>
    <td colspan="2" style="width:200px">
        <asp:GridView ID="GridView1" runat="server" Width="366px" OnRowCommand="GridView1_RowCommand"
            AutoGenerateColumns="False" DataKeyNames="id" Height="186px"
            onrowdeleting="GridView1_RowDeleting" onrowediting="GridView1_RowEditing">
            <Columns>
                <asp:TemplateField HeaderText="Emp Id">
                <ItemTemplate>
                <asp:Label ID="lblid" runat="server" Text='<%#bind("id") %>'>'</asp:Label>
                </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Emp Name">
                <ItemTemplate>
                <asp:Label ID="lblname" runat="server" Text='<%#bind("name") %>'>'</asp:Label>
                </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Phone">
                <ItemTemplate>
                <asp:Label ID="lblphone" runat="server" Text='<%#bind("phone") %>'>'</asp:Label>
                </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Edit">
                <ItemTemplate>
                <asp:Button ID="editbtn" runat="server" CommandName="edit" CausesValidation="false" Text="Edit" ToolTip="Edit" />
                </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Delete">
                <ItemTemplate>
                <asp:Button ID="deletebtn" runat="server" CommandName="delete" CausesValidation="false" Text="Delete" ToolTip="Delete" OnClientClick="ConfirmOnDelete();" />
                </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
        </td>
    <td style="width:200px">
       
        </td>
    </tr>
        </table>
    </div>
    </form>
</body>
</html>

aspx.cs code

using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.Sql;
using System.Configuration;
using System.IO;
public partial class sk : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conn"].ToString());
    SqlCommand cmd;
    SqlDataAdapter da;
    DataSet ds = new DataSet();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            show();
        }
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        if (Button1.ToolTip == "Insert")
        {
            con.Open();
            string str = "insert into text(id,name,phone) values(@id,@name,@phone)";
            cmd = new SqlCommand(str, con);
            cmd.Parameters.AddWithValue("@id", TextBox1.Text);
            cmd.Parameters.AddWithValue("@name", TextBox2.Text);
            cmd.Parameters.AddWithValue("@phone", TextBox3.Text);
            cmd.ExecuteNonQuery();
            Response.Write("<script>alert('Record saved!')</script>");
            con.Close();
            show();
        }
        else if (Button1.ToolTip == "Update")
        {
            int id = Convert.ToInt32(ViewState["pid"]);
            update(id);
        }
       
    }
    public void show()
    {
        con.Open();
        da = new SqlDataAdapter("select *from text",con);
        da.Fill(ds);
        GridView1.DataSource = ds;
        GridView1.DataBind();
        con.Close();
        //GridView2.DataSource = ds;
        //GridView2.DataBind();
    }
   
    protected void Btnedit_Click(object sender, EventArgs e)
    {
        //string id = GridView1.SelectedDataKey.ToString();
        string a = GridView1.SelectedIndex.ToString();
        con.Open();
        string str = "select *from text where id='" + a + "'";
        cmd = new SqlCommand(str, con);
        SqlDataReader dr;
        dr = cmd.ExecuteReader();
        if (dr.HasRows)
        {
            dr.Read();
            TextBox1.Text = dr[0].ToString();
            TextBox2.Text = dr[1].ToString();
            TextBox3.Text = dr[2].ToString();
        }

    }
    protected void Searchbtn_Click(object sender, EventArgs e)
    {
        con.Open();
        string str = "select *from text where id='"+TextBox1.Text+"'";
        cmd = new SqlCommand(str, con);
        SqlDataReader dr;
        dr = cmd.ExecuteReader();
        if (dr.HasRows)
        {
            dr.Read();
            //TextBox1.Text = dr[0].ToString();
            TextBox2.Text = dr[1].ToString();
            TextBox3.Text = dr[2].ToString();
        }

    }
   
     protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {

    }
    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {

    }
    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "edit")
        {
            Button btn = (Button)e.CommandSource;
            GridViewRow grdrow = ((GridViewRow)btn.NamingContainer);
            //Console.Write("<script>alert(empid)</script>");
            //ViewState["id"] = e.CommandArgument;
            Label id = (Label)grdrow.FindControl("lblid");
            Label name = (Label)grdrow.FindControl("lblname");
            Label phone = (Label)grdrow.FindControl("lblphone");
            TextBox1.Text = id.Text;
            TextBox2.Text = name.Text;
            TextBox3.Text = phone.Text;
            Button1.ToolTip = "Update";
            Button1.Text = "Update";
            btn_cancle.Visible = true;      
            int empid = Convert.ToInt32(GridView1.DataKeys[grdrow.RowIndex].Values["id"].ToString());
            ViewState["pid"] = empid.ToString();
            //update(empid)     
        }
        if (e.CommandName == "delete")
        {
            Button btn = (Button)e.CommandSource;
            GridViewRow grdrow = ((GridViewRow)btn.NamingContainer);
            int empid = Convert.ToInt32(GridView1.DataKeys[grdrow.RowIndex].Values["id"].ToString());
            //string str = "delete from text where id=" + empid + "";
            string str = "update text set isactive=0 where id=" + empid + "";
            cmd = new SqlCommand(str,con);
            con.Open();
            cmd.ExecuteNonQuery();
            Response.Write("<script>alert('Record deleted secussfully...')</script>");
            con.Close();
            show();

        }
    }
    public void update(int id)
    {
        int pid = id;
        string str = "update text set name=@name,phone=@phone where id="+pid+"";
        cmd = new SqlCommand(str, con);
        cmd.Parameters.AddWithValue("@name", TextBox2.Text);
        cmd.Parameters.AddWithValue("@phone", TextBox3.Text);
        con.Open();
        cmd.ExecuteNonQuery();
        Console.Write("<script>alert('Record saved!')</script>");
        con.Close();
        show();
    }
    protected void btn_cancle_Click(object sender, EventArgs e)
    {
        Button1.Text = "Insert";
        btn_cancle.Visible = false;
        TextBox1.Text = "";
        TextBox2.Text = "";
        TextBox3.Text = "";
    }
    protected void btn_clear_Click(object sender, EventArgs e)
    {
        TextBox1.Text = "";
        TextBox2.Text = "";
        TextBox3.Text = "";
    }
}

Select Record from one Gridview and show in other Gridview
.aspx code:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style type="text/css">
    .FooterStyle
{
    background-color: #a33;
    color: White;
    text-align: right;
}
    </style>

    <script type = "text/javascript">
<!--
        function Check_Click(objRef) {
            //Get the Row based on checkbox
            var row = objRef.parentNode.parentNode;

            //Get the reference of GridView
            var GridView = row.parentNode;

            //Get all input elements in Gridview
            var inputList = GridView.getElementsByTagName("input");

            for (var i = 0; i < inputList.length; i++) {
                //The First element is the Header Checkbox
                var headerCheckBox = inputList[0];

                //Based on all or none checkboxes
                //are checked check/uncheck Header Checkbox
                var checked = true;
                if (inputList[i].type == "checkbox" && inputList[i] != headerCheckBox) {
                    if (!inputList[i].checked) {
                        checked = false;
                        break;
                    }
                }
            }
            headerCheckBox.checked = checked;

        }
        function checkAll(objRef) {
            var GridView = objRef.parentNode.parentNode.parentNode;
            var inputList = GridView.getElementsByTagName("input");
            for (var i = 0; i < inputList.length; i++) {
                var row = inputList[i].parentNode.parentNode;
                if (inputList[i].type == "checkbox" && objRef != inputList[i]) {
                    if (objRef.checked) {
                        inputList[i].checked = true;
                    }
                    else {
                        if (row.rowIndex % 2 == 0) {
                            row.style.backgroundColor = "#C2D69B";
                        }
                        else {
                            row.style.backgroundColor = "white";
                        }
                        inputList[i].checked = false;
                    }
                }
            }
        }
//-->
</script>

</head>
<body>
    <form id="form1" runat="server">
    <div>
    <div>
    <asp:GridView ID="GV1" runat="server"
        AutoGenerateColumns = "false" Font-Names = "Arial"
        Font-Size = "11pt" AlternatingRowStyle-BackColor = "#C2D69B" 
        HeaderStyle-BackColor = "green" AllowPaging ="true"  
        OnPageIndexChanging = "OnPaging" PageSize = "10" Width="345px"
            ShowFooter="true" FooterStyle-CssClass="FooterStyle"
            onrowdatabound="GV1_RowDataBound" >
<Columns>
<asp:TemplateField>
    <HeaderTemplate>
      <asp:CheckBox ID="chkAll" runat="server" onclick = "checkAll(this);"
        AutoPostBack = "true" OnCheckedChanged = "CheckBox_CheckChanged"  />
    </HeaderTemplate>
    <ItemTemplate>
      <asp:CheckBox ID="chk" runat="server" onclick = "Check_Click(this)"
            AutoPostBack = "true" OnCheckedChanged = "CheckBox_CheckChanged"   />
    </ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField = "emp_id" HeaderText = "Emp Id" HtmlEncode = "false" />
<asp:BoundField DataField = "emp_name" HeaderText = "Emp Name" HtmlEncode = "false" />
<asp:BoundField DataField = "phone" HeaderText = "Phone" HtmlEncode = "false" />
<asp:BoundField HeaderText="Salary" DataField="Salary" />
</Columns>
<AlternatingRowStyle BackColor="#C2D69B"  />

<HeaderStyle BackColor="Green"></HeaderStyle>
</asp:GridView>
<hr />

<div>
<asp:GridView ID="GVSelected" runat="server"
AutoGenerateColumns = "false" Font-Names = "Arial"
Font-Size = "11pt" AlternatingRowStyle-BackColor = "#C2D69B"
HeaderStyle-BackColor = "green" EmptyDataText = "No Records Selected"
        Width="346px"  >
<Columns>
<asp:BoundField DataField = "emp_id" HeaderText = "Emp Id" HtmlEncode = "false" />
<asp:BoundField DataField = "emp_name" HeaderText = "Emp Name" HtmlEncode = "false" />
<asp:BoundField DataField = "phone" HeaderText = "Phone" HtmlEncode = "false" />
<asp:BoundField HeaderText="Salary" DataField="Salary" />
 </Columns>
</asp:GridView>

</div>
    </div>
    </div>
    </form>
</body>
</html>
aspx.cs 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;
using System.Data.SqlClient;
using System.Configuration;

public partial class Gridview2 : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conn"].ToString());
    SqlDataAdapter da;
    DataSet ds = new DataSet();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            grid_bind();
         
        }
    }

    public void grid_bind()
    {
        try
        {
            con.Open();
            da = new SqlDataAdapter("select *from skgridview1", con);
            da.Fill(ds);
            GV1.DataSource = ds;
            GV1.DataBind();
            con.Close();

        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    private void BindSeconGrid()
    {

        DataTable dt = (DataTable)ViewState["SelectedRecords"];
        GVSelected.DataSource = dt;
        GVSelected.DataBind();
    }

    private void GetData()
    {

        DataTable dt;
        if (ViewState["SelectedRecords"] != null)
            dt = (DataTable)ViewState["SelectedRecords"];
        else
            dt = CreateDataTable();
        CheckBox chkAll = (CheckBox)GV1.HeaderRow.Cells[0].FindControl("chkAll");
        for (int i = 0; i < GV1.Rows.Count; i++)
        {
            if (chkAll.Checked)
            {
                dt = AddRow(GV1.Rows[i], dt);
            }
            else
            {
                CheckBox chk = (CheckBox)GV1.Rows[i].Cells[0].FindControl("chk");
                if (chk.Checked)
                {
                    dt = AddRow(GV1.Rows[i], dt);
                }
                else
                {
                    dt = RemoveRow(GV1.Rows[i], dt);
                }
            }
        }

        ViewState["SelectedRecords"] = dt;

    }

    private void SetData()
    {
        CheckBox chkAll = (CheckBox)GV1.HeaderRow.Cells[0].FindControl("chkAll");
        chkAll.Checked = true;

        if (ViewState["SelectedRecords"] != null)
        {
            DataTable dt = (DataTable)ViewState["SelectedRecords"];
            for (int i = 0; i <= GV1.Rows.Count - 1; i++)
            {
                CheckBox chk = (CheckBox)GV1.Rows[i].Cells[0].FindControl("chk");
                if (chk != null)
                {
                    DataRow[] dr = dt.Select("emp_id = '" + GV1.Rows[i].Cells[1].Text + "'");
                    chk.Checked = dr.Length > 0;
                    if (!chk.Checked)
                    {
                        chkAll.Checked = false;
                    }
                }
            }
        }
    }

    private DataTable CreateDataTable()
    {

        DataTable dt = new DataTable();

        dt.Columns.Add("emp_id");
        dt.Columns.Add("emp_name");
        dt.Columns.Add("phone");
        dt.Columns.Add("Salary");
        dt.AcceptChanges();
        return dt;

    }

    private DataTable AddRow(GridViewRow gvRow, DataTable dt)
    {

        DataRow[] dr = dt.Select("emp_id = '" + gvRow.Cells[1].Text + "'");

        if (dr.Length <= 0)
        {
            dt.Rows.Add();
            dt.Rows[dt.Rows.Count - 1]["emp_id"] = gvRow.Cells[1].Text;
            dt.Rows[dt.Rows.Count - 1]["emp_name"] = gvRow.Cells[2].Text;
            dt.Rows[dt.Rows.Count - 1]["phone"] = gvRow.Cells[3].Text;
            dt.Rows[dt.Rows.Count - 1]["Salary"] = gvRow.Cells[4].Text;
            dt.AcceptChanges();

        }

        return dt;

    }

    private DataTable RemoveRow(GridViewRow gvRow, DataTable dt)
    {

        DataRow[] dr = dt.Select("emp_id = '" + gvRow.Cells[1].Text + "'");

        if (dr.Length > 0)
        {
            dt.Rows.Remove(dr[0]);
            dt.AcceptChanges();
        }

        return dt;

    }

    protected void GV1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GetData();
        GV1.PageIndex = e.NewPageIndex;
        grid_bind();
        SetData();
    }

    protected void chk_CheckedChanged(object sender, EventArgs e)
    {
        GetData();
        SetData();
        BindSeconGrid();
    }
  
    protected void OnPaging(object sender, GridViewPageEventArgs e)
    {
        GetData();
        GV1.PageIndex = e.NewPageIndex;
        grid_bind();
        SetData();
    }
    protected void CheckBox_CheckChanged(object sender, EventArgs e)
    {
        GetData();
        SetData();
        BindSeconGrid();
    }
}
Demo
Emp IdEmp NamePhoneSalary
57reeta896527841525500.0000
58reeta896527841525500.0000
73ram459856210525000.0000
74ram459856210525000.0000
75ram459856210525000.0000
76ram459856210525000.0000
77ram459856210525000.0000
78ram459856210525000.0000
79ram459856210525000.0000
80ram459856210525000.0000
     
12

Emp IdEmp NamePhoneSalary
73ram459856210525000.0000
74ram459856210525000.0000
76ram459856210525000.0000
Sum of Gridview column 
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style type="text/css">
    .FooterStyle
{
    background-color: #a33;
    color: White;
    text-align: right;
}
    </style>

</head>
<body>
    <form id="form1" runat="server">
    <div>
    <div>
    <asp:GridView ID="GV1" runat="server"
        AutoGenerateColumns = "false" Font-Names = "Arial"
        Font-Size = "11pt" AlternatingRowStyle-BackColor = "#C2D69B" 
        HeaderStyle-BackColor = "green" AllowPaging ="true"  
        PageSize = "10" Width="345px"
            ShowFooter="true" FooterStyle-CssClass="FooterStyle" >
<Columns>
<asp:TemplateField HeaderText="Emp Id">
<ItemTemplate>
<asp:Label ID="lblid" runat="server" Text='<%#Eval("emp_id") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Emp Name">
<ItemTemplate>
<asp:Label ID="lblname" runat="server" Text='<%#Eval("emp_name") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Phone">
<ItemTemplate>
<asp:Label ID="lblphone" runat="server" Text='<%#Eval("phone") %>' />
</ItemTemplate>
<FooterTemplate>
<asp:Label ID="lbltotal" runat="server" Text="Total Salary"></asp:Label>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Salary">
<ItemTemplate>
<asp:Label ID="lblsalary" runat="server" Text='<%#Eval("salary") %>' />
</ItemTemplate>
<FooterTemplate>
<asp:Label ID="lblsum" runat="server"></asp:Label>
</FooterTemplate>
</asp:TemplateField>
</Columns>
<AlternatingRowStyle BackColor="#C2D69B"  />

<HeaderStyle BackColor="Green"></HeaderStyle>
</asp:GridView>
   
    </div>
    </div>
    </form>
</body>
</html>
.cs code
public partial class GridView2_sum_ofcolumn : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conn"].ToString());
    SqlDataAdapter da;
    DataSet ds = new DataSet();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            grid_bind();

        }
    }

    public void grid_bind()
    {
        try
        {
            con.Open();
            //string str = "skgridview1_ins";
            da = new SqlDataAdapter("select *from skgridview1",con);
            da.Fill(ds);
            GV1.DataSource = ds;
            GV1.DataBind();
            con.Close();   
((Label)GV1.FooterRow.Cells[1].FindControl("lblsum")).Text = ds.Tables[0].Compute("sum(salary)", "").ToString();
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
}

OR

 private decimal _TotalsalTotal = 0;
    protected void GV1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                decimal Totalsal = (decimal)DataBinder.Eval(e.Row.DataItem, "Salary");
                _TotalsalTotal += Totalsal;
            }
            if (e.Row.RowType == DataControlRowType.Footer)
            {
                Label lblSummary = (Label)e.Row.FindControl("lblsum");
                lblSummary.Text = String.Format("{0:c}", _TotalsalTotal);
            }
        }
First,open the visual studio 2008

Next,select one Asp Web Application and click ok

Next download one Gif image for to show loading

Next,Open the design page of Default.aspx

Next,Drag and drop one UpdatePanel,one textbox from the toolbox

Next,In that Updatepanel Drag and drop one Link button and label

Next,add one image

Next,Come to the Source page of default.aspx page

Next,code will be look like this


<asp:UpdatePanel ID="UpdatePanel1" runat="server" >
    <ContentTemplate>              
      <div id="divImage" style="display:none">
       <asp:Image ID="img1" runat="server" ImageUrl="~/images/ajax-loader.gif" />
                     Processing...
                </div>              
                <br />          
          
                    <asp:LinkButton ID="lb_checkavail" runat="server" CausesValidation="False"
                        Font-Underline="False" onClick="lb_checkavail_Click"
                    style="font-weight: 700" ForeColor="#00CCFF">Check Availability</asp:LinkButton><br />
                    <asp:Label ID="lbl_msg1" runat="server" Font-Bold="True"
                    Font-Names="Verdana" ForeColor="#FF9933"></asp:Label></ContentTemplate>
        </asp:UpdatePanel>


Now,come to the code page of Default.aspx.cs

write the following code for the link button

protected void lb_checkavail_Click(object sender, EventArgs e)
    {
        con = new SqlConnection(ConfigurationManager.ConnectionStrings["SAMPLE_2"].ToString());
        con.Open();
        com = new SqlCommand("select * from Users where Username='"+txt_uname.Text+"'",con);
        dr = com.ExecuteReader();
        if (dr.Read())
        {
                lbl_msg1.Text = "Not Availble";
                this.lbl_msg1.ForeColor = Color.DarkGreen;        
        }
        else
        {
            if (txt_uname.Text == "")
            {
                lbl_msg1.Text = "Please Enter the Username";
            }
            else
            {
                lbl_msg1.Text = "Available";
            }
        }
    }

Finally execute the page.....Thats it...

Wednesday 30 May 2012

Validation using JavaScript in Asp.net


This simple program will guide how to do client side validation of Form in JavaScript.
In this just make a form as follows:
  1. Name : <asp:TextBox ID="txtName" />
  2. Email : <asp:TextBox ID="txtEmail" />
  3. Web URL : <asp:TextBox ID="txtWebUrl" />
  4. Zip : <asp:TextBox ID="txtZip" />
  5. <asp:Button ID="btnSubmit" OnClientClick=" return validate()" runat="server" Text="Submit" />
Now on the source code of this form in script tag write the following code:
<script language="javascript" type="text/javascript">
function
validate()
{
      if (document.getElementById("<%=txtName.ClientID%>").value==""
)
      {
                 alert("Name Feild can not be blank"
);
                 document.getElementById(
"<%=txtName.ClientID%>"
).focus();                 return false;
      }
      if(document.getElementById("<%=txtEmail.ClientID %>").value==""
)
      {
                 alert(
"Email id can not be blank"
);                document.getElementById("<%=txtEmail.ClientID %>").focus();                return false;
      }
     var
emailPat = /^(\".*\"|[A-Za-z]\w*)@(\[\d{1,3}(\.\d{1,3}){3}]|[A-Za-z]\w*(\.[A-Za-z]\w*)+)$/;     var emailid=document.getElementById("<%=txtEmail.ClientID %>").value;     var matchArray = emailid.match(emailPat);     if (matchArray == null)
    {
               alert(
"Your email address seems incorrect. Please try again."
);
               document.getElementById(
"<%=txtEmail.ClientID %>"
).focus();               return false;
    }
    if(document.getElementById("<%=txtWebURL.ClientID %>").value==""
)
    {
               alert(
"Web URL can not be blank"
);
               document.getElementById(
"<%=txtWebURL.ClientID %>").value=
"http://"               document.getElementById("<%=txtWebURL.ClientID %>").focus();               return false;
    }
    var Url=
"^[A-Za-z]+://[A-Za-z0-9-_]+\\.[A-Za-z0-9-_%&\?\/.=]+$"    var tempURL=document.getElementById("<%=txtWebURL.ClientID%>").value;    var matchURL=tempURL.match(Url);     if(matchURL==null)
     {
               alert(
"Web URL does not look valid"
);
               document.getElementById(
"<%=txtWebURL.ClientID %>"
).focus();               return false;
     }
     if (document.getElementById("<%=txtZIP.ClientID%>").value==""
)
     {
               alert(
"Zip Code is not valid"
);
               document.getElementById(
"<%=txtZIP.ClientID%>"
).focus();               return false;
     }
     var digits="0123456789"
;     var temp;     for (var i=0;i<document.getElementById("<%=txtZIP.ClientID %>").value.length;i++)
     {
               temp=document.getElementById(
"<%=txtZIP.ClientID%>"
).value.substring(i,i+1);               if (digits.indexOf(temp)==-1)
               {
                        alert(
"Please enter correct zip code"
);
                        document.getElementById(
"<%=txtZIP.ClientID%>"
).focus();                        return false;
               }
     }
     return true
;
}
</script>

And in code behind file just write the below code.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
               btnSubmit.Attributes.Add(
"onclick", "return validate()"
)End Sub
Send Email Code in Asp.net

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="SendMail.aspx.cs" Inherits="SendMail" %>
 
<head runat="server"><title>title></head>
<body>
    <form id="form1" runat="server">
        Message to: <asp:TextBox ID="txtTo" runat="server" /><br>
        Message from: <asp:TextBox ID="txtFrom" runat="server" /><br>
        Subject: <asp:TextBox ID="txtSubject" runat="server" /><br>
        Message Body:<br>
        <asp:TextBox ID="txtBody" runat="server" Height="171px" TextMode="MultiLine" Width="270px" /><br>
        <asp:Button ID="Btn_SendMail" runat="server" onclick="Btn_SendMail_Click" Text="Send Email" /><br>
        <asp:Label ID="Label1" runat="server" Text="Label">asp:Label>
    </form>
</body>
</html>
 
 .cs Code
using System;
using System.Web.UI.WebControls;
using System.Net.Mail;
public partial class SendMail : System.Web.UI.Page
{
    protected void Btn_SendMail_Click(object sender, EventArgs e)
    {
        MailMessage mailObj = new MailMessage(
            txtFrom.Text, txtTo.Text, txtSubject.Text, txtBody.Text);
        SmtpClient SMTPServer = new SmtpClient("localhost");
        try
        {
           SMTPServer.Send(mailObj);
        }
            catch (Exception ex)
        {
            Label1.Text = ex.ToString();
        }
    }
}
 

Tuesday 29 May 2012

Set Login name and Logout button on master page 

Step 1) First we create a master page and add two link button as Login and Logout
Code for Master page: Master.aspx
<div class="loginDisplay">
                <asp:Label ID="Loginname" runat="server"></asp:Label><br />             
                <asp:LinkButton ID="link1" runat="server" Text="Logout" Visible="False"
                        onclick="link1_Click"></asp:LinkButton> 
            </div>
Master.cs code:
      protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (Session["ll"] == null)
            {
               
            }
        }
        }
    protected void link1_Click(object sender, EventArgs e)
    {
        Response.Redirect("Login.aspx");
    }
step 2: Create a Login Page
Login.aspx  code
<fieldset style="width:400px; height:200px;">
<legend>Login</legend>
<table style="height: 156px; width: 340px">
<tr>
<td colspan="2">
<asp:Label ID="lblmsg" runat="server" CssClass="label" Height="16px" Width="273px"></asp:Label>
</td>
</tr>
<tr>
<td>User Id <span class="style1">*</span></td>
<td><asp:TextBox ID="txtuserid" runat="server" Height="22px" Width="180px"></asp:TextBox></td>
</tr>
<tr>
<td>Password <span class="style2">*</span></td>
<td><asp:TextBox ID="txtpass" runat="server" Height="22px" Width="180px" TextMode="Password"></asp:TextBox></td>
</tr>
<tr>
<td></td>
<td><asp:Button ID="btnlogin" runat="server" Text="Login" BackColor="#660066"
        Font-Bold="True" ForeColor="White" onclick="btnlogin_Click" /></td>
</tr>
<tr>
<td colspan="2">
&nbsp;Forgot Password?</td>
</tr>
</table>
</fieldset>


Login.cs code

public partial class _Default : System.Web.UI.Page
{
    SqlConnection con = new  
    SqlConnection(ConfigurationManager.ConnectionStrings["conn"].ToString());
    SqlDataAdapter da;
    SqlCommand cmd;
    SqlDataReader dr;
    DataSet ds;
    protected void Page_Load(object sender, EventArgs e)
    {
       
    }
    protected void btnsave_Click(object sender, EventArgs e)
    {
        con.Open();
        cmd = new SqlCommand("sklogin_ins", con);
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.AddWithValue("@id", txtuserid.Text);
        cmd.Parameters.AddWithValue("@pass", txtpass.Text);
        cmd.ExecuteNonQuery();

        SqlDataAdapter sqlAdap = new SqlDataAdapter(cmd);
        ds = new DataSet();
        sqlAdap.Fill(ds);

        if (ds.Tables[0].Rows.Count > 0)
        {
            Session["log"] = ds.Tables[0].Rows[0]["userid"].ToString();
            Response.Redirect("Default.aspx");
        }
        else
        {
            lblmsg.Text = "userid and password does not match";
            txtuserid.Text = "";
            txtpass.Text = "";
        }
    }
}
step 3: Now Create Default.aspx page


Default.cs code:






protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            LinkButton link1 = (LinkButton)Master.FindControl("link1");
            link1.Visible = true;
            string login = Session["log"].ToString();

            Session["ll"] = login;
            Label lbl1 = (Label)Master.FindControl("Loginname");
            lbl1.Text = "hi"+" : "+" "+login.ToString();
        }
    }