Friday 31 May 2013

how to bind gridview using Jquery in asp.net .

Introduction:-

In this article , I have explained how to bind GridView using Jquery in asp.net. For this I have used jquery with ajax, because we cannot call method without using Ajax .

First Create a table:-

Create table login(userid varchar(50),password varchar(50), type varchar(50), status varchar(50));
Insert some dummy data in the table.

Drag and drop GridView Control on design page.

JQuery Code:-

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "GVBindUsingJQuery.aspx/BindGridView",
data: "{}",
dataType: "json",
success: function(data) {
for (var i = 0; i < data.d.length; i++) {
$("#GridView1").append("<tr><td>" + data.d[i].userid + "</td><td>" + data.d[i].password + "</td><td>" + data.d[i].type + "</td><td>" + data.d[i].status + "</td></tr>");
}
},
error: function(result) {
alert("Error");
}
});
});
</script>
<style type="text/css">
table,th,td
{
border:1px solid black;
border-collapse:collapse;
}
</style>
Full Code:-
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "GVBindUsingJQuery.aspx/BindGridView",
data: "{}",
dataType: "json",
success: function(data) {
for (var i = 0; i < data.d.length; i++) {
$("#GridView1").append("<tr><td>" + data.d[i].userid + "</td><td>" + data.d[i].password + "</td><td>" + data.d[i].type + "</td><td>" + data.d[i].status + "</td></tr>");
}
},
error: function(result) {
alert("Error");
}
});
});
</script>
<style type="text/css">
table,th,td
{
border:1px solid black;
border-collapse:collapse;
}
</style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server">
        <HeaderStyle BackColor="#DC5807" Font-Bold="true" ForeColor="White" />
        </asp:GridView>
    </div>
    </form>
</body>
</html>

Code behind Page:-

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;
using System.Web.Services;
using System.Text;
using System.Collections.Generic;
public partial class GVBindUsingJQuery : System.Web.UI.Page
{
    string constr = ConfigurationManager.ConnectionStrings["khamaconn"].ConnectionString;
    //MySqlConnection con;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.IsPostBack)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("userid");
            dt.Columns.Add("password");
            dt.Columns.Add("type");
            dt.Columns.Add("status");
            dt.Rows.Add();
            GridView1.DataSource = dt;
            GridView1.DataBind();
            GridView1.Rows[0].Visible = false;
        }
    }
    [WebMethod]
    public static LoginDetails[] BindGridView()
    {
        DataTable dt = new DataTable();
        List<LoginDetails> details = new List<LoginDetails>();
        using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conn"].ConnectionString))
        {
            using (SqlCommand cmd = new SqlCommand("Select * from login",con))
            {
                con.Open();
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                da.Fill(dt);
                foreach(DataRow dtrow in dt.Rows)
                {
                    LoginDetails login = new LoginDetails();
                    login.userid=dtrow["userid"].ToString();
                    login.password = dtrow["password"].ToString();
                    login.type = dtrow["type"].ToString();
                    login.status = dtrow["status"].ToString();
                    details.Add(login);
                }
            }
        }
        return details.ToArray();
    }
    public class LoginDetails
    {
        public string userid {get;set;}
        public string password { get; set; }
        public string type { get; set; }
        public string status { get; set; }
    }
}

Run the code and test.


Tuesday 28 May 2013

How to send Bulk email in asp.net using c#.

Introduction:-

In the previous article , I have have explained how to send email in asp.net using c#. In this article I have explained how to send bulk email in asp.net using c#. Suppose that you have 50 email and your want to send them all at a time.

Let's create a table in which you have the following fields..

 id, name, emailid,country, state,city
 Insert the data in the table.

Now if you want to send the mail on button click event if you are using sql database. then read the table and use for loop for taking email id one by one.

for connection:-

string constr = ConfigurationManager.ConnectionStrings["sushilconn"].ConnectionString;

Code on button click event:-

protected void Button1_Click(object sender, EventArgs e)

    {
        con.Open();
        MySqlCommand cmd = new MySqlCommand("Select emailid from details", con);
        MySqlDataAdapter da = new MySqlDataAdapter(cmd);
        DataTable dt = new DataTable();
        da.Fill(dt);
        for (int i = 0;i< dt.Rows.Count;i++ )
        {
            string id=dt.Rows[i].ItemArray[0].ToString();
            MailMessage mail = new MailMessage();
            mail.To.Add(id);
            mail.From = new MailAddress("youremailid@gmail.com");
            mail.Subject = "Email using Gmail";

            string Body = "Hi, this mail is to test sending mail" +
                          "using Gmail in ASP.NET";
            mail.Body = Body;

            mail.IsBodyHtml = true;
            SmtpClient smtp = new SmtpClient();
            smtp.Host = "smtp.gmail.com"; //Or Your SMTP Server Address
            smtp.Credentials = new System.Net.NetworkCredential
                 ("youremailid@gmail.com", "yourpassword");
            //Or your Smtp Email ID and Password
            smtp.EnableSsl = true;
            smtp.Send(mail);

        }
}

The Above code send the mail one by one.

How to send email using gmail credential in asp.net using c#.

Introduction:-

In this article . I have explained how to send email using Gmail credential in asp.net. Using Gmail credential , you have required your gmailid and gmail password for sending a meil to someone. There are also antother way to send mail using SMTP server in asp.net , but using SMTP server only emailId required for sending email.
 
Design page like this:-

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        From :<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <br />
        To :
        <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
        <br />
        Subject :<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
        <br />
        Body :<asp:TextBox ID="TextBox4" runat="server" Height="39px"
            TextMode="MultiLine"></asp:TextBox>
        <br />
        <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
    </div>
    </form>
</body>

</html>

Don't forget to add following namespace in .cs page.

using System.Net.Mail;

Code Behind Page:-

protected void Button1_Click(object sender, EventArgs e)
    {
        
            MailMessage mail = new MailMessage();
            mail.To.Add(TextBox2.Text);
            mail.From = new MailAddress(TextBox1.Text);
            mail.Subject = TextBox3.Text;

            string Body = TextBox4.Text;
            mail.Body = Body;

            mail.IsBodyHtml = true;
            SmtpClient smtp = new SmtpClient();
            smtp.Host = "smtp.gmail.com"; //Or Your SMTP Server Address
            smtp.Credentials = new System.Net.NetworkCredential
                 ("youremailid@gmail.com", "gmailpasword");
            //Or your Smtp Email ID and Password
            smtp.EnableSsl = true;
            smtp.Send(mail);
        }

    }

Run the code and test.
If any query regarding this article , feel free to ask.

Monday 27 May 2013

How to convert GridView Column into HyperLink in asp.net.

Introduction:-

In this article , I have explained how to convert gridview column into hyperlink.

Design the page like this:-

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
        <Columns>
            <asp:HyperLinkField  runat="server" DataTextField="name" DataNavigateUrlFields="id" DataNavigateUrlFormatString="~/Details.aspx?id{0}" HeaderText="Name"/>
            <asp:BoundField DataField="Emailid" HeaderText="EmailId" />
        </Columns>
        </asp:GridView>

//Details.aspx page is another page on which you redirect to see details according to id.

Bind GridView:-

protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.IsPostBack)
        {
            DataTable dt = new DataTable();
            dt.Columns.AddRange(new DataColumn[4] { new DataColumn("id"), new DataColumn("name"), new DataColumn("Emailid"), new DataColumn("mobileno") });
            dt.Rows.Add(1,"Sushil Kumar","sushil@gmail.com","9874563258");
            dt.Rows.Add(2,"Muthu Kumar","muthu@gmail.com","5896574125");
            dt.Rows.Add(3,"Ashutosh Ojha","ashu@gmail.com","8745214789");
            dt.Rows.Add(4,"Sanjay wadhawa","sanjay@gmail.com","9852475635");
            GridView1.DataSource = dt;
            GridView1.DataBind();
        }
    }


Wednesday 22 May 2013

Trim() function in asp.net using c#.

Introduction:-


 In this article , I have explained Trim() function in c#. Trim() is used for removing leading and trailing white-space character. If the current string is empty or all the current instance is white-space then function return empty value.

Example:-

TextBox1.Text.Trim();

This will remove all leading and trailing white-space character from input string.

Monday 20 May 2013

How to Disable resizable of multiline textbox in asp.net.

Introduction:-

In this article , I have explained how to disable resizable properties of textbox in asp.net.
Take a textbox on design page and set this property style like

style="resize:none"

Example:-

<asp:TextBox ID="TextBox1" runat="server" TextMode="MultiLine" style="resize:none"></asp:TextBox>

You can also done by using CSS .

<style type="text/css">
textarea
{
     resize:none;
}

</style>

Friday 17 May 2013

Laod data on scroll in GridView in asp.net using Jquery with Ajax.

Introduction:-

In this article , I have described how to laod data on demand in Gridview in asp.net using Jquery with Ajax. For this I have used Jquery with Ajax and Stored procedure.It better to go through by practicle approach.


First Make a table in DataBase and stored procedure for this table.

Table Structure:-

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[Customers](
            [CustomerID] [int] NULL,
            [CompanyName] [varchar](max) NULL,
            [ContactName] [varchar](max) NULL,
            [City] [varchar](max) NULL,
            [Country] [varchar](max) NULL,
            [PostalCode] [int] NULL,
            [Phone] [int] NULL,
            [Fax] [int] NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO

SET ANSI_PADDING OFF
GO

Stored Procedure:-

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[GetCustomersPageWise]
      @PageIndex INT = 1
      ,@PageSize INT = 10
      ,@PageCount INT OUTPUT
AS
BEGIN
      SET NOCOUNT ON;
      SELECT ROW_NUMBER() OVER
            (
                  ORDER BY [CustomerID] ASC
            )AS RowNumber
      ,[CustomerID]
      ,[CompanyName]
      ,[ContactName]
      ,[City]
      ,[Country]
      ,[PostalCode]
      ,[Phone]
      ,[Fax]
    INTO #Results
      FROM [Customers]
   
      DECLARE @RecordCount INT
      SELECT @RecordCount = COUNT(*) FROM #Results

      SET @PageCount = CEILING(CAST(@RecordCount AS DECIMAL(10, 2)) / CAST(@PageSize AS DECIMAL(10, 2)))
      PRINT       @PageCount
         
      SELECT * FROM #Results
      WHERE RowNumber BETWEEN(@PageIndex -1) * @PageSize + 1 AND(((@PageIndex -1) * @PageSize + 1) + @PageSize) - 1
   
      DROP TABLE #Results
END

Now open your visual studio and create one project -> Open Design Page -> drag and drop one gridview control to design page.

Design the page like this:-

<!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 id="Head1" runat="server">
    <title></title>
    <style type="text/css">
        .Grid td
        {
            background-color: #A1DCF2;
            color: black;
            font-size: 10pt;
            font-family: Arial;
            line-height: 200%;
            cursor: pointer;
            width: 100px;
        }
        .Grid th
        {
            background-color: #3AC0F2;
            color: White;
            font-family: Arial;
            font-size: 10pt;
            line-height: 200%;
            width: 100px;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
  <table class="Grid" cellspacing="0" rules="all" border="1" id="Table1" style="width:500px;border-collapse:collapse;">
                        <tr>
                                    <th scope="col" style="width:200px;">Customer Name</th><th scope="col" style="width:100px;">City</th><th scope="col" style="width:100px;">Country</th><th scope="col" style="width:100px;">Postal Code</th>
                        </tr>
    </table>
<div id="dvGrid" style="height: 250px; overflow: auto; width: 517px">
<asp:GridView ID="gvCustomers" runat="server" AutoGenerateColumns="false" CssClass="Grid" Width = "500">
    <Columns>
        <asp:BoundField DataField="ContactName" HeaderText = "Customer Name" ItemStyle-CssClass="name" ItemStyle-Width="200" HeaderStyle-Width="200" />
        <asp:BoundField DataField="City" HeaderText = "City" ItemStyle-CssClass="city" ItemStyle-Width="100" HeaderStyle-Width="100" />
        <asp:BoundField DataField="Country" HeaderText = "Country" ItemStyle-CssClass="country" ItemStyle-Width="100" HeaderStyle-Width="100" />
        <asp:BoundField DataField="PostalCode" HeaderText = "Postal Code" ItemStyle-CssClass="postal" ItemStyle-Width="100" HeaderStyle-Width="100" />
    </Columns>
</asp:GridView>
</div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
    var pageIndex = 1;
    var pageCount;
    $(function () {
        //Remove the original GridView header
        $("[id$=gvCustomers] tr").eq(0).remove();
    });

    //Load GridView Rows when DIV is scrolled
    $("#dvGrid").on("scroll", function (e) {
        var $o = $(e.currentTarget);
        if ($o[0].scrollHeight - $o.scrollTop() <= $o.outerHeight()) {
            GetRecords();
        }
    });

    //Function to make AJAX call to the Web Method
    function GetRecords() {
        pageIndex++;
        if (pageIndex == 2 || pageIndex <= pageCount) {

            //Show Loader
            if ($("[id$=gvCustomers] .loader").length == 0) {
                var row = $("[id$=gvCustomers] tr").eq(0).clone(true);
                row.addClass("loader");
                row.children().remove();
                row.append('<td colspan = "999" style = "background-color:white"><img id="loader" alt="" src="103.gif"  /></td>');
                $("[id$=gvCustomers]").append(row);
            }
            $.ajax({
                type: "POST",
                url: "ScrollGridView.aspx/GetCustomers",
                data: '{pageIndex: ' + pageIndex + '}',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: OnSuccess,
                failure: function (response) {
                    alert(response.d);
                },
                error: function (response) {
                    alert(response.d);
                }
            });
        }
    }

    //Function to recieve XML response append rows to GridView
    function OnSuccess(response) {
        var xmlDoc = $.parseXML(response.d);
        var xml = $(xmlDoc);
        pageCount = parseInt(xml.find("PageCount").eq(0).find("PageCount").text());
        var customers = xml.find("Customers");
        $("[id$=gvCustomers] .loader").remove();
        customers.each(function () {
            var customer = $(this);
            var row = $("[id$=gvCustomers] tr").eq(0).clone(true);
            $(".name", row).html(customer.find("ContactName").text());
            $(".city", row).html(customer.find("City").text());
            $(".postal", row).html(customer.find("PostalCode").text());
            $(".country", row).html(customer.find("Country").text());
            $("[id$=gvCustomers]").append(row);
        });

        //Hide Loader
        $("#loader").hide();
    }
</script>
    </form>
</body>
</html>

Code behind 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;
using System.Web.Services;
using System.Configuration;
using System.Data.SqlClient;
using System.Collections;
using System.Web.Security;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
public partial class ScrollGridView : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            gvCustomers.DataSource = GetCustomersPageWise(1, 10);
            gvCustomers.DataBind();
        }
    }
    public static DataSet GetCustomersPageWise(int pageIndex, int pageSize)
    {
        string constring = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        using (SqlConnection con = new SqlConnection(constring))
        {
            using (SqlCommand cmd = new SqlCommand("GetCustomersPageWise"))
            {
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@PageIndex", pageIndex);
                cmd.Parameters.AddWithValue("@PageSize", pageSize);
                cmd.Parameters.Add("@PageCount", SqlDbType.Int, 4).Direction = ParameterDirection.Output;
                using (SqlDataAdapter sda = new SqlDataAdapter())
                {
                    cmd.Connection = con;
                    sda.SelectCommand = cmd;
                    using (DataSet ds = new DataSet())
                    {
                        sda.Fill(ds, "Customers");
                        DataTable dt = new DataTable("PageCount");
                        dt.Columns.Add("PageCount");
                        dt.Rows.Add();
                        dt.Rows[0][0] = cmd.Parameters["@PageCount"].Value;
                        ds.Tables.Add(dt);
                        return ds;
                    }
                }
            }
        }
    }
    [WebMethod]
    public static string GetCustomers(int pageIndex)
    {
        //Added to similate delay so that we see the loader working
        //Must be removed when moving to production
        System.Threading.Thread.Sleep(2000);

        return GetCustomersPageWise(pageIndex, 10).GetXml();
    }
}

Run the code and Check the Output.