Thursday, September 15, 2011

Sending Email in asp.net, C#

You can write this code at the click event of a button in asp.net to automatically send an email whenever the button is clicked :- 

{
SmtpClient smtpClient = new SmtpClient();
smtpClient.Host = "10.9.210.53"; // IP address of an SMTP server
smtpClient.Port = 25; //Port No of the SMTP server

MailMessage objMail = new MailMessage("sender email id", "receiver's email id ");
objMail.IsBodyHtml = true;
objMail.Subject = " Set here the subject of mail";
objMail.Body = "Hi!! How are you ";
objMail.Priority = MailPriority.High; // Set if waant to send mail with high priority
NetworkCredential nc = new NetworkCredential("username of network admin", "password");
nc.Domain = "domain name";
smtpClient.Credentials = nc;
smtpClient.Send(objMail);
Response.Write("Email has been sent successfully.");
}

Tuesday, August 30, 2011

GridView Insert, Edit, Update, Delete, Sorting

This demo describes the basic way to do INSERT, EDIT, UPDATE ,DELETE and SORTING data in ASPNET GridView Control using the ADO.NET way.

STEP  1: Creating  a DataBase Table.


Create a database names neeraj containing a table named Login.
Following must be the design of the table Login


Column           Datatype
    

User_ID    nvarchar(5)
User_Name    nvarchar(50)
Password    nvarchar(50)




STEP 2: Setting Up the Connection String

   <connectionStrings>
    <add name="DBConnection" connectionString="Data Source=GDC-DELL-PC17\SQLEXPRESS;Initial Catalog=neeraj;Integrated Security=True"/>
  </connectionStrings>
 


STEP 3: Creating GridView

<asp:Label ID="lblSortDirection" runat="server"></asp:Label>
    <asp:GridView ID="GridView1"
                  runat="server"
                  AutoGenerateColumns="False
                  AutoGenerateEditButton="True
                  onrowcancelingedit="GridView1_RowCancelingEdit
                  onrowediting="GridView1_RowEditing
                  onrowupdating="GridView1_RowUpdating
                  ShowFooter="True
                  AutoGenerateDeleteButton="True
                  onrowdeleting="GridView1_RowDeleting
                  
            AllowSorting="True" onsorting="GridView1_Sorting" AllowPaging="True" 
           PageSize="3" onpageindexchanging="GridView1_PageIndexChanging1"   
             >
        <PagerSettings PageButtonCount="1" />
        <Columns>
            <asp:TemplateField HeaderText="User_ID" SortExpression="User_ID">
                <ItemTemplate>
                    <asp:Label ID="lblUserId" runat="server" Text='<%# Eval("User_ID") %>'></asp:Label>
                </ItemTemplate>
                
                <FooterTemplate>
                    <asp:TextBox ID="txtInsertUserId" runat="server"></asp:TextBox>
                </FooterTemplate>
                <FooterStyle VerticalAlign="Top" />
            </asp:TemplateField>
            <asp:TemplateField HeaderText="User_Name" SortExpression="User_Name">
                <ItemTemplate>
                    <asp:Label ID="lblUserName" runat="server" Text='<%# Eval("User_Name") %>'></asp:Label>
                </ItemTemplate>
                <EditItemTemplate>
                    <asp:TextBox ID="txtEditUserName" runat="server" Text='<%# Bind("User_Name") %>' ></asp:TextBox>
                </EditItemTemplate>
                <FooterTemplate>
                    <asp:TextBox ID="txtInsertUserName" runat="server"></asp:TextBox>
                </FooterTemplate>
                <FooterStyle VerticalAlign="Top" />
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Password" SortExpression="Password">
                <ItemTemplate>
                    <asp:Label ID="lblPassword" runat="server" Text='<%# Eval("Password") %>'></asp:Label>
                </ItemTemplate>
                <EditItemTemplate>
                    <asp:TextBox ID="txtEditPassword" runat="server" Text='<%# Bind("Password") %>'></asp:TextBox>
                </EditItemTemplate>
                <FooterTemplate>
                    <asp:TextBox ID="txtInsertPassword" runat="server"></asp:TextBox>
                    <br />
                    <asp:Button ID="btnInsert" runat="server" onclick="btnInsert_Click" 
                        Text="Insert" />
                    <asp:Button ID="btnCancel" runat="server" Text="Cancel" OnClick="btnCancel_Click" />
                </FooterTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>



STEP 4: Binding GridView with Data



public partial class _Default : System.Web.UI.Page
{
    string strSortExpression;


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


    private string GetConnectionString()
    {
        return System.Configuration.ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;
    }



 protected void fillgrid()
    {
        SqlConnection conn = new SqlConnection(GetConnectionString());
        DataTable dt = new DataTable();


        try
        {
            
            conn.Open();
            string query = "select * from Login";
            SqlCommand cmd = new SqlCommand(query, conn);
            SqlDataAdapter adp = new SqlDataAdapter(cmd);
            adp.Fill(dt);
            if (dt.Rows.Count &gt; 0)
            {
                GridView1.DataSource = dt;
                GridView1.DataBind();
            }
            else
            {
                GridView1.Visible = false;
                Response.Write("No data to display!!!");
            }
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
        }
        finally
        {
            conn.Close();
        }
    }


STEP 5: InsertNew Data in GridView



 protected void btnInsert_Click(object sender, EventArgs e)
    {


        SqlConnection conn = new SqlConnection(GetConnectionString());
        try
        {
            conn.Open();


            string user_name = ((TextBox)GridView1.FooterRow.FindControl("txtInsertUserName")).Text;
            string pwd = ((TextBox)GridView1.FooterRow.FindControl("txtInsertPassword")).Text;
            string id = ((TextBox)GridView1.FooterRow.FindControl("txtInsertUserId")).Text;


            Response.Write(user_name);
            Response.Write(pwd);
            Response.Write(id);


            if (user_name != "" &amp;&amp; pwd != "" &amp;&amp; id != "")
            {
                SqlCommand cmd = new SqlCommand("STP_insertLogin", conn);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.Add("@user_name", SqlDbType.VarChar).Value = user_name;
                cmd.Parameters.Add("@user_id", SqlDbType.VarChar).Value = id;
                cmd.Parameters.Add("@pwd", SqlDbType.VarChar).Value = pwd;
                cmd.ExecuteNonQuery();
                conn.Close();
                fillgrid();
                clear();
            }
            else
            {
                Response.Write("Please insert proper values");
            }
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
        }
        finally
        {
            conn.Close();
        }
    }




protected void btnCancel_Click(object sender, EventArgs e)
    {
        clear();
    }


    protected void clear()
    {
        ((TextBox)GridView1.FooterRow.FindControl("txtInsertUserName")).Text = "";
        ((TextBox)GridView1.FooterRow.FindControl("txtInsertPassword")).Text = "";
        ((TextBox)GridView1.FooterRow.FindControl("txtInsertUserId")).Text = "";
    }




STEP 6: Edit and Update Records In GridView



 protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        GridView1.EditIndex = e.NewEditIndex;
        fillgrid();
    }


    protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        GridView1.EditIndex = -1;
        fillgrid();
    }


    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        SqlConnection conn = new SqlConnection(GetConnectionString());
        try
        {
            conn.Open();


            string user_name = ((TextBox)GridView1.Rows[e.RowIndex].Cells[1].Controls[0].FindControl("txtEditUserName")).Text;
            string pwd = ((TextBox)GridView1.Rows[e.RowIndex].Cells[2].Controls[0].FindControl("txtEditPassword")).Text;
            string id = ((Label)GridView1.Rows[e.RowIndex].Cells[0].Controls[0].FindControl("lblUserId")).Text;


            SqlCommand cmd = new SqlCommand("usp_UpdateUserMaster", conn);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Add("@User_Name", SqlDbType.VarChar).Value = user_name;
            cmd.Parameters.Add("@Password", SqlDbType.VarChar).Value = pwd;
            cmd.Parameters.Add("@User_ID", SqlDbType.VarChar).Value = id;
            cmd.ExecuteNonQuery();
            conn.Close();
            GridView1.EditIndex = -1;
            fillgrid();
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
        }
        finally
        {
            conn.Close();
        }
    }


STEP 7: Perform Delete in GridView



protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
                
            SqlConnection conn = new SqlConnection(GetConnectionString());
            try
            {
                conn.Open();
                string id = ((Label)GridView1.Rows[e.RowIndex].Cells[0].Controls[0].FindControl("lblUserId")).Text;
                SqlCommand cmd = new SqlCommand("STP_deleteLogin", conn);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.Add("@user_id", SqlDbType.VarChar).Value = id;
                cmd.ExecuteNonQuery();
                fillgrid();
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }
            finally
            {
                conn.Close();
            }
            
    }


STEP 8: Perform Sorting in GridView



 protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
    {
        strSortExpression = (string)ViewState["SortExpression"];
        DataTable dt = dt_return();
        if (lblSortDirection.Text == " ASC" &amp;&amp; strSortExpression == e.SortExpression)
        {
            lblSortDirection.Text = " DESC";
            ViewState["SortExpression"] = e.SortExpression;
            strSortExpression = (string)ViewState["SortExpression"];
        }
        else
        {
            lblSortDirection.Text = " ASC";
            ViewState["SortExpression"] = e.SortExpression;
             strSortExpression = (string)ViewState["SortExpression"];
        }
        
        dt.DefaultView.Sort = strSortExpression + lblSortDirection.Text;
        GridView1.DataSource = dt.DefaultView;
        GridView1.DataBind();
    }

Monday, August 29, 2011

Export GridView Data to Excel

In this article I will explain how you can export your GridView control to Excel files.
The following code executes on a button click event.


protected void btnExcel_Click(object sender, EventArgs e)
{
//ExportToExcel();

gvTDefaulters.AllowPaging = false;
gvTDefaulters.AllowSorting = false;
gvTDefaulters.EditIndex = -1;



this.BindData(); // Populate Gridview with data

Response.Clear();
Response.ContentType = "application/vnd.xls";
Response.AddHeader("content-disposition", "attachment;filename=FileName.xls");


StringWriter swriter = new StringWriter();
HtmlTextWriter hwriter = new HtmlTextWriter(swriter);

HtmlForm frm = new HtmlForm();
this.gvTDefaulters.Parent.Controls.Add(frm);
frm.Attributes["runat"] = "server";
frm.Controls.Add(this.gvTDefaulters);
frm.RenderControl(hwriter);

Response.Write(swriter.ToString());
Response.End();
}

Now if you try to export your GridView to excel it will work fine.

Friday, May 23, 2008

Hi everybody!!!!

This is my first blogging experience.....i am very excited about it.....i hope to continue it in future enthusiastically.....i expect support,visits and comments from everybody.

Thank u

with love....Ravi