Saturday, February 18

how to export gridview data to Excel or how to export gridview data to word document using asp.net or Export gridview data to Excelsheet, Word document using asp.net

Introduction: 

Here I will explain how to export gridviewdata to Word and Excel using asp.net.


Description:
I have one gridview that has filled with user details now I need to export gridview data to word or excel document based on selection. To implement this functionality first we need to design aspx page like this 

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td align="right">
<asp:ImageButton ID="btnExcel" runat="server" ImageUrl="~/ExcelImage.jpg"
onclick="btnExcel_Click" />
<asp:ImageButton ID="btnWord" runat="server" ImageUrl="~/WordImage.jpg"
onclick="btnWord_Click" />
</td>
</tr>
<tr>
<td>
<asp:GridView runat="server" ID="gvdetails" DataSourceID="dsdetails"  AllowPaging="true"AllowSorting="true" AutoGenerateColumns="false">
<RowStyle BackColor="#EFF3FB" />
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:BoundField DataField="UserId" HeaderText="UserId" />
<asp:BoundField DataField="UserName" HeaderText="UserName" />
<asp:BoundField DataField="LastName" HeaderText="LastName" />
<asp:BoundField DataField="Location" HeaderText="Location" />
</Columns>
</asp:GridView>
</td>
</tr>
</table>
<asp:SqlDataSource ID="dsdetails" runat="server"ConnectionString="<%$ConnectionStrings:dbconnection %>"
SelectCommand="select * from UserInformation"/>
</div>
</form>
</body>
</html>
Here don’t forgot to set the connection string in web.config file here I am getting database connection from web.config file for that reason you need to set the connectionstring in web.config file like this 

<connectionStrings>
<add name="dbconnection" connectionString="Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB"/>
</connectionStrings>
After set the connection string in web.config file now we are able to get the data from database and we can bind that data to gridview by using sqldatasource. Now if you run application gridview appears like this


Now in code behind add this reference

using System.IO;
After that write the following code in code behind

public override void VerifyRenderingInServerForm(Control control)
{
/* Verifies that the control is rendered */
}
/// <summary>
/// This event is used to export gridview data to word document
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void btnWord_Click(object sender, ImageClickEventArgs e)
{
gvdetails.AllowPaging = false;
gvdetails.DataBind();
Response.ClearContent();
Response.AddHeader("content-disposition"string.Format("attachment; filename={0}","Customers.doc"));
Response.Charset = "";
Response.ContentType = "application/ms-word";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gvdetails.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}
/// <summary>
/// This Event is used to export gridview data to Excel
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void btnExcel_Click(object sender, ImageClickEventArgs e)
{
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition"string.Format("attachment; filename={0}""Customers.xls"));
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gvdetails.AllowPaging = false;
gvdetails.DataBind();
//Change the Header Row back to white color
gvdetails.HeaderRow.Style.Add("background-color""#FFFFFF");
//Applying stlye to gridview header cells
for (int i = 0; i < gvdetails.HeaderRow.Cells.Count; i++)
{
gvdetails.HeaderRow.Cells[i].Style.Add("background-color""#507CD1");
}
int j = 1;
//This loop is used to apply stlye to cells based on particular row
foreach (GridViewRow gvrow in gvdetails.Rows)
{
gvrow.BackColor = Color.White;
if (j <= gvdetails.Rows.Count)
{
if (j % 2 != 0)
{
for (int k = 0; k < gvrow.Cells.Count; k++)
{
gvrow.Cells[k].Style.Add("background-color""#EFF3FB");
}
}
}
j++;
}
gvdetails.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}

Demo for Word document


If you observe above code I added one function that is VerifyRenderingInServerForm this function is used to avoid the error like “control must be placed in inside of form tag”. If we setVerifyRenderingInServerForm function then compiler will think that controls rendered before exporting and our functionality will work perfectly.

Here I used basic code to export gridview data to word document and for excel code is different but we can use the same code (Export to Word) for excel also to import gridview data just by replacingCustomers.doc to Customers.xls and application/ms-word to application/ms-excel but here we have problem that is row background color is applied throughout excel for that reason I made some small code modification and applied color only to the particular columns based on rows.

Demo for Excel document


Download sample code attached






Now if you’re getting any error message like 

Control 'gvdetails' of type 'GridView' must be placed inside a form tag with runat=server



Thanks shibashish mohanty

Friday, February 17

INSERT IN TO MYSQL WITH ASP.NET


Here are the scripts you’ll need to create the verse schema (database). To execute the scripts, you’ll need to use the mysql command line utility or MySQL Query Browser application. You can create any database with this table and change the database name.

CREATE TABLE IF NOT EXISTS `membership` (

  `id` int(11) NOT NULL AUTO_INCREMENT,

  `first_name` varchar(25) NOT NULL,

  `last_name` varchar(25) NOT NULL,

  `username` varchar(25) NOT NULL,

  `password` varchar(10) NOT NULL,

  `email_address` varchar(50) NOT NULL,

  PRIMARY KEY (`id`)

) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;

we have to use MySql.Data.MySqlClient; to use mysql database.

We use ? as mysql Parameters.

Here is the html markup code





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


<!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>Insert Into Mysql with asp.net</title>


</head>




<body>

    <form id="form1" runat="server" a>


    <div>

<table width="300px" >


    <tr>


    <td>First Name</td>
    <td>


        <asp:TextBox ID="txtFirstName" runat="server"></asp:TextBox>
        </td>


    </tr>


        <tr>



    <td >Last Name</td>


    <td>


        <asp:TextBox ID="txtLastName" runat="server"></asp:TextBox>


            </td>


    </tr>


        <tr>


    <td>User Name</td>



    <td>





        <asp:TextBox ID="txtUserName" runat="server"></asp:TextBox>




            </td>


    </tr>


        <tr>


    <td>Password</td>
    <td>


        <asp:TextBox ID="txtPassword" runat="server"></asp:TextBox>
       </td>


    </tr>


        <tr>



    <td>Email Address</td>


    <td>




        <asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>


            </td>


    </tr>


        <tr>




    <td>&nbsp;</td>




    <td>



        <asp:Button ID="btnSave" runat="server" Text="Save" onclick="btnSave_Click" />


       </td>


    </tr>



        <tr>




    <td>&nbsp;</td>


    <td>


        <asp:Label ID="lblError" runat="server" Text=""></asp:Label>




            </td>


    </tr>


    </table>




    </div>




    </form>




</body>


</html>



Here’s the C# 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;

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

    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        try
        {
            string connectn = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
            SqlConnection con;
            SqlCommand cmd;
            string comstring = "INSERT INTO membership (first_name ,last_name ,username ,password ,";
            comstring += "email_address)VALUES (@first_name ,@last_name ,@username ,@password ,@email_address);";
            con = new SqlConnection(connectn);
            cmd = new SqlCommand(comstring, con);
            cmd.CommandType = CommandType.Text;
            cmd.Parameters.Add("@first_name", SqlDbType.VarChar).Value = txtFirstName.Text;
            cmd.Parameters.Add("@last_name", SqlDbType.VarChar).Value = txtLastName.Text;
            cmd.Parameters.Add("@username", SqlDbType.VarChar).Value = txtUserName.Text;
            cmd.Parameters.Add("@password",SqlDbType.VarChar).Value = txtPassword.Text;
            cmd.Parameters.Add("@email_address", SqlDbType.VarChar).Value = txtEmail.Text;
            con.Open();
            int result = cmd.ExecuteNonQuery();
            lblError.Text = "data inserted successfully";

        }

        catch
        {
            lblError.Text = "error occured";
        }
    }
}

My web.config connection strings



<connectionStrings>
<add name="ConnectionString" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True" providerName="System.Data.SqlClient"/>
</connectionStrings>



Bellow is the html form picture and successful message after insert data in to mysql database.



You can download the full code with the MySql.Data.MySqlClient; DLL

Download



Thanks Shibashish Mohanty. 

Thursday, February 16

Send Sms Using Way to sms Dll

Source code:


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

<!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>Shibashish mohanty</title>
    <style type="text/css">
        .style1
        {
            width: 34%;
            height: 99px;
        }
        .style2
        {
            width: 133px;
        }
        .style3
        {
            width: 35px;
        }
        .style4
        {
            width: 26px;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div align="center" >
 
        <table class="style1"
            style="background-position: center center; border: thick solid #C0C0C0;"
            bgcolor="#336600">
            <tr>
                <td class="style4" style="color: #FFFFFF">
                    To:</td>
                <td class="style2">
                   <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox></td>
                <td class="style3">
                    &nbsp;</td>
                <td style="color: #FFFFFF">
                    Msg:</td>
                <td>
                   <asp:TextBox ID="TextBox2" TextMode="MultiLine" runat="server"></asp:TextBox></td>
            </tr>
            <tr>
                <td class="style4">
                    &nbsp;</td>
                <td class="style2">
                    &nbsp;</td>
                <td class="style3">
                    &nbsp;</td>
                <td>
                    &nbsp;</td>
                <td>
                    &nbsp;</td>
            </tr>
            <tr>
                <td class="style4">
                    &nbsp;</td>
                <td class="style2">
                    &nbsp;</td>
                <td class="style3">
                    <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Send" />
                </td>
                <td>
                    &nbsp;</td>
                <td>
                    &nbsp;</td>
            </tr>
            <tr>
                <td class="style4">
                    &nbsp;</td>
                <td class="style2">
                    &nbsp;</td>
                <td class="style3">
                    &nbsp;</td>
                <td>
                    &nbsp;</td>
                <td>
                    &nbsp;</td>
            </tr>
        </table>
        <br />
        <table class="style1"
         
         
         
            style="background-position: center center; border: thick solid #990000; position: fixed; border-collapse: collapse; display: block; background-color: #333300; top: 188px; left: 461px;">
            <tr>
                <td class="style4" style="color: #FFFFFF">
                    UserID:</td>
                <td class="style2">
                   <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox></td>
                <td class="style3">
                    &nbsp;</td>
                <td style="color: #FFFFFF">
                    Password:</td>
                <td>
                   <asp:TextBox ID="TextBox4" TextMode="Password" runat="server"></asp:TextBox></td>
            </tr>
            <tr>
                <td class="style4">
                    &nbsp;</td>
                <td class="style2">
                    &nbsp;</td>
                <td class="style3">
                    &nbsp;</td>
                <td>
                    &nbsp;</td>
                <td>
                    &nbsp;</td>
            </tr>
            <tr>
                <td class="style4">
                    &nbsp;</td>
                <td class="style2">
                    &nbsp;</td>
                <td class="style3">
                    &nbsp;</td>
                <td>
                    &nbsp;</td>
                <td>
                    &nbsp;</td>
            </tr>
            <tr>
                <td class="style4">
                    &nbsp;</td>
                <td class="style2">
                    &nbsp;</td>
                <td class="style3">
                    &nbsp;</td>
                <td>
                    &nbsp;</td>
                <td>
                    &nbsp;</td>
            </tr>
        </table>
 
    </div>
    </form>
</body>
</html>

Code Behind:-

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.IO; 
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    public void send(string uid, string password, string message, string no)
    {
        HttpWebRequest myReq =
        (HttpWebRequest)WebRequest.Create("http://ubaid.tk/sms/sms.aspx?uid=" + uid + "&pwd=" + password +
        "&msg=" + message + "&phone=" + no + "&provider=way2sms");

        HttpWebResponse myResp = (HttpWebResponse)myReq.GetResponse();
        System.IO.StreamReader respStreamReader = new System.IO.StreamReader(myResp.GetResponseStream());
        string responseString = respStreamReader.ReadToEnd();
        respStreamReader.Close();
        myResp.Close();
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        send(TextBox3.Text,TextBox4.Text, TextBox2.Text, TextBox1.Text);
    }
}

Thanks Shibashish mohanty

Thursday, February 2

Select all text in textbox on click.

You can do it in the client side it self.
Just try this...
<asp:TextBox ID="txt1" runat="server" Text="Abc" onfocus="javascript:this.select();" ></asp:TextBox>
otherwise if you want to do it in the code behind
write
txt1.Attributes.Add("onfocus","javascript:this.select();");
this in your page load event.


Thanks shibashish mohanty

.

ShibashishMnty
shibashish mohanty