Wednesday, May 16, 2012

Deletion of multiple records in GridView using Checkbox in ASP.NET.




deletion of record in gridview using checkbox(multiple row deletion)in aspx.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.Collections.Specialized;
public partial class _Default : System.Web.UI.Page
{
   
    SqlCommand cmd;
    SqlDataAdapter da;
    SqlConnection con = new SqlConnection("data source=RAJAT\\SQLEXPRESS;initial catalog= master;integrated security=sspi;");
    protected void Page_Load(object sender, EventArgs e)
    {
       
    }



    protected void Gridview1_SelectedIndexChanged(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        StringCollection idCollection = new StringCollection();
        string strID = string.Empty;

        for (int i = 0; i < Gridview1.Rows.Count; i++)
        {
            CheckBox Checkbox1 = (CheckBox)
               Gridview1.Rows[i].Cells[0].FindControl("Checkbox1");
            if (Checkbox1 != null)
            {
                if (Checkbox1.Checked)
                {
                    strID = Gridview1.Rows[i].Cells[1].Text;
                    idCollection.Add(strID);
                }
            }
        }
        DeleteMultipleRecords(idCollection);
        Gridview1.DataBind();

    }
    private void DeleteMultipleRecords(StringCollection idCollection)
    {
        //Create sql Connection and Sql Command
        //con.Open();
        SqlCommand cmd = new SqlCommand();
        string IDs = "";

        foreach (string id in idCollection)
        {
            IDs += id.ToString() + ",";
        }
        try
        {
            string strIDs =
             IDs.Substring(0, IDs.LastIndexOf(","));
            foreach (string id in idCollection)
            {
                string strSql = ("Delete from aparna  WHERE id in ('" + id + "')");
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = strSql;
                cmd.Connection = con;
                con.Open();
                cmd.ExecuteNonQuery();
                con.Close();
            }
        }
        catch (SqlException ex)
        {
            string errorMsg = "Error in Deletion";
            errorMsg += ex.Message;
            throw new Exception(errorMsg);
        }
        finally
        {
            con.Close();
        }
    }
}

code in .aspx page :-

---------------------------------------

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <div>

<asp:GridView ID="Gridview1" runat ="server" AutoGenerateColumns ="false"
        DataSourceID ="sqldatasource1" ShowFooter ="true"
        onselectedindexchanged="Gridview1_SelectedIndexChanged">
<Columns >
<asp:TemplateField >
<ItemTemplate >
<asp:CheckBox ID="Checkbox1" runat ="server" />
</ItemTemplate>
<FooterTemplate >
<asp:Button ID="Button1" runat ="server" Text ="DELETE" OnClick="Button1_Click" OnClientClick ="return DeleteConfirmation();" />
</FooterTemplate>
</asp:TemplateField>
<asp:BoundField DataField ="id" HeaderText ="ID" />
<asp:BoundField DataField ="name" HeaderText ="NAME" />
<asp:BoundField DataField ="location" HeaderText ="LOCATION" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID ="sqldatasource1" runat ="server" ConnectionString ="Data Source=RAJAT\SQLEXPRESS;Initial Catalog=master;Integrated Security=True" SelectCommand ="select [id],[name],[location] from [aparna]">
</asp:SqlDataSource>
</div>
    </asp:Content>




code in master page(site master page);-

-----------------------------------------------------------------------

<head runat="server">
    <title></title>
    <link href="~/Styles/Site.css" rel="stylesheet" type="text/css" />
    <asp:ContentPlaceHolder ID="HeadContent" runat="server">
    </asp:ContentPlaceHolder>
    <script type="text/javascript" language="javascript">
function DeleteConfirmation()
{
if (confirm("Are you sure you want to delete selected records ?")==true)
   return true;
else
   return false;
}
</script>

</head>

How to convert a Number into words in C#


Convert Number To Words in ASP.Net
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
public partial class Default2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
decimal iAmt = Convert.ToDecimal(Label1.Text);
string strAmount = wordify(iAmt);
Label2.Text = strAmount;
}
static string wordify(decimal v)
{
if (v == 0) return "zero";
var units = "|One|Two|Three|Four|Five|Six|Seven|Eight|Nine".Split('|');
var teens = "|eleven|twelve|thir#|four#|fif#|six#|seven#|eigh#|nine#".Replace("#", "teen").Split('|');
var tens = "|Ten|Twenty|Thirty|Forty|Fifty|Sixty|Seventy|Eighty|Ninety".Split('|');
var thou = "|Thousand|m#|b#|tr#|quadr#|quint#|sex#|sept#|oct#".Replace("#", "illion").Split('|');
var g = (v < style="color: rgb(163, 21, 21);">"minus " : "";
var w = "";
var p = 0;
v = Math.Abs(v);
while (v > 0)
{
int b = (int)(v % 1000);
if (b > 0)
{
var h = (b / 100);
var t = (b - h * 100) / 10;
var u = (b - h * 100 - t * 10);
var s = ((h > 0) ? units[h] + " Hundred" + ((t > 0 | u > 0) ? " and " : "") : "") + ((t > 0) ? (t == 1 && u > 0) ? teens[u] : tens[t] + ((u > 0) ? "-" : "") : "") + ((t != 1) ? units[u] : ""); s = (((v > 1000) && (h == 0) && (p == 0)) ? " and " : (v > 1000) ? ", " : "") + s; w = s + " " + thou[p] + w;
} v = v / 1000; p++;
}
return g + w ;
}
}
OutPut :
Number : 98563 

Number in Words: Ninety-Eight Thousand, Five Hundred and Sixty-Three

How to work on 3-Layer architecture in .NET


                                                   
When we work on Layered architecture we follow some techniques to do work on it.
The main purpose of this technique is for security purpose.

                                                                Layer -1
                                                       ==============

METHOD FOR DAL(Date Access Layer) :
=================================
Here we have to define number of methods related to Database access.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Net;
using System.Net.Mail;

/// <summary>
/// Summary description for InvoiceDAL
/// </summary>
public class InvoiceDAL : System.Web.UI.Page
{
    SqlConnection con;
    SqlCommand cmd;
    SqlDataReader dr;
    DataTable dt;
    public static int i, j, k;
    public string[] arr = new string[1000];
    public InvoiceDAL()
    {
        con = new SqlConnection(HttpContext.Current.Session["connection"].ToString());     //Connection             defined on web.config File.
    }
    public int insert(string invoiceId, string Subject, int SalesOrderId, int AccountId,
                      string CustomerName, string PhoneNo)
    {
        con.Open();
        cmd = new SqlCommand("select Id_int from Base_SalesOrder", con);
        dr = cmd.ExecuteReader();
        dr.Read();
        i = Convert.ToInt32(dr[0].ToString());
        Session["SalesOrderId"] = i;
        dr.Close();
        con.Close();
        con.Open();

        cmd = new SqlCommand("select [Id_int] from Base_PurchaseOrder", con);
        dr = cmd.ExecuteReader();
        dr.Read();
        k = Convert.ToInt32(dr[0].ToString());
        Session["PurchaseOrderId"] = k;
        dr.Close();
        con.Close();
        con.Open();
        SqlCommand Cmd = new SqlCommand("insert_invoice6", con);
        Cmd.CommandType = CommandType.StoredProcedure;

        try
        {
            Cmd.Parameters.AddWithValue("@InvoiceId_vc", invoiceId);
            Cmd.Parameters.AddWithValue("@Subject_vc", Subject);
            Cmd.Parameters.AddWithValue("@SalesOrderId_int", i);
            Cmd.Parameters.AddWithValue("@AccountId_int", j);
            Cmd.Parameters.AddWithValue("@CustomerName_vc", CustomerName);
            Cmd.Parameters.AddWithValue("@CompanyName_vc", CompanyName);
            Cmd.Parameters.AddWithValue("@PhoneNo_vc", PhoneNo);
            return Cmd.ExecuteNonQuery();

        }

        catch
        {

            throw;

        }

        finally
        {



            Cmd.Dispose();

            con.Close();

            con.Dispose();



        }
    }
}


                                                                   Layer-2
                                                            ===========
METHOD FOR BAL(Business  Access Layer) :
=================================

Here, we define a object of DAL and access the DAL's Method.
BAL works as a intermedeate layer and used for the security purpose.
The code is here..


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using System.Data;

/// <summary>
/// Summary description for invoiceBAL
/// </summary>
public class invoiceBAL : System.Web.UI.Page
{
    InvoiceDAL objDAL = new InvoiceDAL();

    public invoiceBAL()
    {
        //
        // TODO: Add constructor logic here
        //
    }
    public int insert(string invoiceId, string Subject, int i, int j,
        string CustomerName, string PhoneNo)
    {
        try
        {

            return objDAL.insert(invoiceId, Subject, i, j, CustomerName, PhoneNo);
        }
        catch
        {

            throw;

        }

        finally
        {

            objDAL = null;

        }

    }
}

                                                             Layer-3
                                                    ============
Method for .CS Page:-
=================
This is the final layer i.e. . CS file.
This is same as the BAL. we only need to create an object of BAL Class and just call the method which defined on BAL.
The  code is ..


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;
using System.Collections;
using System.Web.UI.WebControls.WebParts;
using System.Web.Security;


public partial class Invoice : ThemeClass
{

 protected void Page_Load(object sender, EventArgs e)
    {

            InvoiceId = lblInvoiceID.Text;
            string Subject = txtsubject.Text;
            if (Button1.Text == "Submit")     //Check the button text i.e. SUBMIT or NOT.
            {
                invoiceBAL objBAL = new invoiceBAL();
                int i = Convert.ToInt32(Session["SalesOrderId"]);
                string CustomerName = txtcustomername.Text;
                string CompanyName = txtcompanyname.Text;
                string PhoneNo = txtphonenumber.Text;
           
                try
                {
                    intResult = objBAL.insert(InvoiceId, Subject, i, j, CustomerName, PhoneNo);
                }
                finally
                {
                    objBAL = null;
                }

                if (Button1.Text == "Submit")
                {
                    InsertData();
                }

            }




Thursday, February 9, 2012

VALIDATION ON TEXT BOX THROUGH JAVA SCRIPT in asp.net

ON FORM LOAD : - .CS FILE
--------------------------
protected void Page_Load(object sender, EventArgs e)
   {
        txtPhone.Attributes.Add("onkeydown", "return isNumeric(event.keyCode);");
       
        txtPhone.Attributes.Add("onkeyup", "keyUP(event.keyCode)");
    } 

  


CODE ON DESIRED TEXT BOX :-
-----------------------------
<asp:TextBox ID="txtPhone" runat="server" onkeyup = "keyUP(event.keyCode)" onkeydown = "return isNumeric(event.keyCode);"></asp:TextBox>




CODE ON MASTER PAGE :-
-----------------------
    function isNumeric(keyCode)
{
      if(keyCode==16)
            isShift = true;

      return ((keyCode >= 48 && keyCode <= 57 || keyCode == 8 ||
            (keyCode >= 96 && keyCode <= 105)) && isShift == false);
}
</script>

Monday, January 16, 2012

How to develop STOP WATCH in asp.net.


HOW TO GENERATE SELF TIMER IN ASP.NET  : -
========================================
   .cs file code:-
-----------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Timers;

public partial class Stop_Watch : System.Web.UI.Page
{
    public int time_second;
    public int time_min;
    protected void Page_Load(object sender, EventArgs e)
    {
        if(!IsPostBack)
            Timer1.Enabled = false;
     
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        Timer1.Enabled = true;
        btnpause.Visible = true;
        btnreset.Visible = true;
   
       
    }
    protected void Timer1_Tick(object sender, EventArgs e)
    {
     
        time_second = int.Parse(lblsec1.Text);
        time_second = time_second + 1;
        lblsec1.Text = time_second.ToString();
        if (lblsec1.Text == "10")
        {
            lblsec2.Visible = false;
        }
        if (lblmin1.Text == "10")
        {
            lblmin2.Visible = true;
        }

        if (lblsec1.Text == "60")
        {
            lblsec2.Visible = true;
            time_min = int.Parse(lblmin1.Text);
            lblsec1.Text = "0";
            time_min = time_min + 1;
            lblmin1.Text = time_min.ToString();
        }

    }
    protected void Button2_Click(object sender, EventArgs e)
    {
       Timer1.Enabled = false;
   
    }



    protected void Button3_Click(object sender, EventArgs e)
    {
        time_second = 0;
        time_min = 0;
        lblmin1.Text = "0";
        lblsec1.Text = "0";
        lblsec2.Visible = true;
        Timer1.Enabled = false;
    }
}
----------------------------------------------------------------------------------

.aspx page code :-
------------------

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Stop_Watch.aspx.cs" Inherits="Stop_Watch" %>

<!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>
    <style type="text/css">
        .style1
        {
            width: 100%;
        }
        .style2
        {
            width: 140px;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server">

/* First you have to insert this SCRIPT MANAGER after form tag. without this, any ajax control doesn't work. */
                    </asp:ScriptManager>
    <div>
   
        <table class="style1">
            <tr>
                <td class="style2">
                    <asp:UpdatePanel ID="UpdatePanel1" runat="server">    

 /* You have to insert this UPLOAD PANEL.The timer will insert under this UPLOAD  PANEL.This will help to refresh only partially like Google search box. */

                        <ContentTemplate>
                            <asp:Timer ID="Timer1" runat="server" Enabled="false" Interval="1000"
                                ontick="Timer1_Tick">
                            </asp:Timer>
                            <asp:Label ID="lblmin2" runat="server" Text="0"></asp:Label>
                            <asp:Label ID="lblmin1" runat="server" Text="0"></asp:Label>
                            <asp:Label ID="Label3" runat="server" Text=":"></asp:Label>
                            <asp:Label ID="lblsec2" runat="server" Text="0"></asp:Label>
                            <asp:Label ID="lblsec1" runat="server" Text="0"></asp:Label>
                        </ContentTemplate>
                    </asp:UpdatePanel>
                   
                </td>
                <td>
                    <asp:Button ID="btnstart" runat="server" OnClientClick ="startTimer()" Text="Start"
                        Width="160px" onclick="Button1_Click" />
                </td>
            </tr>
            <tr>
                <td class="style2">
                    &nbsp;</td>
                <td>
                    <asp:Button ID="btnpause" runat="server" Text="Pause"
                        OnClientClick = "stopTimer()" onclick="Button2_Click" Width="76px"  />
                    <asp:Button ID="btnreset" runat="server" Text="Reset" onclick="Button3_Click"
                        Width="79px" />
                </td>
            </tr>
        </table>
   
    </div>
    </form>
    <script type = "text/javascript">
    function startTimer() {

       return $find('Timer1')._startTimer();

    }
    function stopTimer() {
       return $find('Timer1')._stopTimer();
    }
    </script>
</body>
</html>
=============================================================================

Saturday, January 14, 2012

How to Send E-Mail Through C# in asp.net.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.Net.Mail;
using System.Data.SqlClient;

public partial class Email : System.Web.UI.Page
{
    SqlConnection con;
    SqlCommand cmd;
    protected void Page_Load(object sender, EventArgs e)
    {
        con = new SqlConnection(@"data source=localhost;initial catalog=Email;integrated security=true");
    }
    protected void btnsave_Click(object sender, EventArgs e)
    {
        con.Open();
        cmd=new SqlCommand("insert into Gmail values('"+DropDownList1.Text+"','"+DropDownList2.Text+"','"+txtusername.Text+"','"+txtpassword.Text+"','"+txtmessage.Text+"')",con);
        cmd.ExecuteNonQuery();
        con.Close();
        Response.Write("Done Successfully");
        MailMessage message = new MailMessage();

        string s1;
        string s2;
        string s3;
        s1 = DropDownList2.SelectedItem.Text;
        s2 = "vibhutimishra58@gmail.com";
        MailAddress fromAddress = new MailAddress(s2);
        s3 = txtusername.Text;
        MailAddress toAddress = new MailAddress(s3);
        message.From = fromAddress;
        message.To.Add(toAddress);
        message.Subject = "Mail Send";
        message.Body = "Message:" + "</br>" + txtmessage.Text;
        if (DropDownList2.SelectedItem.Text == "smtp.gmail.com")
        {
            SmtpClient smtp = new SmtpClient();
            smtp.Port = 587;
            smtp.Host = s1;
            smtp.Credentials = new System.Net.NetworkCredential(s2, "confirm12m*");
            smtp.EnableSsl = true;
            smtp.Send(message);
            txtmessage.Text = "";
        }
        else if (DropDownList2.SelectedItem.Text == "smtp.mail.yahoo.com")
        {
            SmtpClient smtp = new SmtpClient();
            smtp.Port = 465;
            smtp.Host = s1;
            smtp.Credentials = new System.Net.NetworkCredential("Your Email Id","Your password");
            smtp.EnableSsl = true;
            smtp.Send(message);
            txtmessage.Text = "";
        }
    }
}