Sunday 22 January 2012

Simple method to send mails form your asp.net


first include

Using System.Net.Mail;

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


protected void Button1_Click(object sender, EventArgs e)
    {
        MailMessage mail = new MailMessage();
        mail.To.Add("manjunath4ualways@gmail.com");
        mail.To.Add("manjunath4ualways@gmail.com");
        mail.From = new MailAddress("manjunath.le@smartdrivelabs.com");
        mail.Subject = "Mail from manju";

        string Body = "Hi, this mail is manju ";
        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
             ("your mail id", "password");
        //Or your Smtp Email ID and Password
        smtp.EnableSsl = false;
        smtp.Send(mail);
    }

thats it........




Simple method to send mails form your asp.net with attachment


first include

Using System.Net.Mail;

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


protected void Button1_Click(object sender, EventArgs e)
    {
        MailMessage mail = new MailMessage();
        mail.To.Add("manjunath4ualways@gmail.com");
        mail.To.Add("manjunath4ualways@gmail.com");
        mail.From = new MailAddress("manjunath.le@smartdrivelabs.com");
        mail.Subject = "Mail from manju";

        string Body = "Hi, this mail is From Manju ";
        mail.Body = Body;

        mail.IsBodyHtml = true;
        if (FileUpload1.HasFile)
        {
            string FileName = System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName);
            mail.Attachments.Add(new Attachment(FileUpload1.PostedFile.InputStream, FileName));
        }


        SmtpClient smtp = new SmtpClient();
        smtp.Host = "smtp.gamil.com"; //Or Your SMTP Server Address
        smtp.Credentials = new System.Net.NetworkCredential
             ("your mailid", "password");
        //Or your Smtp Email ID and Password
        smtp.EnableSsl = false;
        smtp.Send(mail);
    }
thats it...............

your SMTP server name means......... the outgoing mail server for your mail id which ll be used in outlook for mail configuration


Wednesday 18 January 2012

stored procedure for inserting records

first create the procedure in the sql server like this

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
ALTER proc [dbo].[comment]
(
@name varchar(50),
@email varchar(50),
@comment varchar(max)
)
as
insert into Commentbox (SE_name,SE_Email,SE_comment) values (@name,@email,@comment)

and then in code behind

 string connstr = ConfigurationManager.ConnectionStrings["smartedu"].ConnectionString;
        SqlConnection conn = new SqlConnection(connstr);
        SqlCommand cmd = new SqlCommand();
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.CommandText = "dbo.comment";
 
        cmd.Parameters.AddWithValue("@name",TextBox1.Text);
        cmd.Parameters.AddWithValue("@email", TextBox2.Text);
        cmd.Parameters.AddWithValue("@comment", TextBox3.Text);
        cmd.Connection = conn;

        try
        {
            conn.Open();
            cmd.ExecuteNonQuery();
        }
        catch (Exception ex)
        {
            Label1.Text = ex.Message;
        }

        TextBox3.Text = "";
        TextBox2.Text = "";
        TextBox1.Text = "";

Friday 13 January 2012

How to make datalist content to scroll from top


   <div id="js1" style="overflow:hidden; left:114px; top:600px; width:810px; height:300px; z-index:0">
   <div align="center" id="c_js1" style="overflow:hidden;height:100%;width:100%;">
     
    <div id="p1_js1">


/// your datalist code



<asp:DataList ID="DataList1" runat="server" Width="627px" >
    <ItemTemplate>
    <div id="selector2">
    <div id="div1" style="padding-left:5px;">
    <asp:Label ID="label1" runat="server"  Text='<%# DataBinder.Eval(Container.DataItem, "SE_eventname")%>' ForeColor="#0099CC" Font-Bold="true" Font-Size="Medium"></asp:Label>
    </div>
    <div id="div2" align="center">
    <asp:TextBox ID="txt1" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "SE_eventdetails")%>' Style="overflow: hidden;resize:none;" Height="30px" TextMode="MultiLine" Width="95%" MaxLength="100" BorderStyle="None" ></asp:TextBox>
    </div>
    <div id="div3" align="right" style="padding-right:5px;">
        <asp:LinkButton ID="LinkButton1" CommandName="view" runat="server">View more</asp:LinkButton>
    </div>
    </div>
    <asp:Button ID="hiddenbutton" Visible="false" Text='<%# DataBinder.Eval(Container.DataItem, "SE_postid")%>' runat="server"/>
    <br />
    </ItemTemplate>
     <AlternatingItemStyle BackColor="White" />

    <ItemStyle BackColor="#FFFBD6" ForeColor="#333333"/>

    <SelectedItemStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
 
    </asp:DataList>


 <br>
</div>
<div id="p2_js1"></div>
</div>



<script language="javascript" type="text/javascript">
var speed=30
var i=0
var n=Math.floor(js1.offsetHeight/p1_js1.offsetHeight)
for (i=0;i<=n;i++)
{
p2_js1.innerHTML+=p1_js1.innerHTML
}
function m_js1()
{
if(c_js1.scrollTop<=p1_js1.offsetTop)
c_js1.scrollTop+=p1_js1.offsetHeight
else{
c_js1.scrollTop--
}
}
var mm_js1=setInterval(m_js1,speed)
c_js1.onmouseover=function(){clearInterval(mm_js1)}
c_js1.onmouseout=function(){mm_js1=setInterval(m_js1,speed)}
</script></div>


thats it.........! it ll scroll the content of the datalist from top

Thursday 12 January 2012

Paging the datalist content with page numbers

your design page looks like this:



    <asp:Label ID="error" runat="server" Text=""></asp:Label>
<div id="selector1" style="font-family:Tahoma;
      font-size:15px;
      font-weight:bold">
 &nbsp;&nbsp;&nbsp;Events and Exhibitions
</div>
<div id="selector" align="center" >
    <div id="div5" align="right">
     Select number of events to be displayed per page<asp:DropDownList ID="ddlIndex" runat="server" AutoPostBack="True"
            onselectedindexchanged="ddlIndex_SelectedIndexChanged">
        </asp:DropDownList>
    </div>
    <asp:DataList ID="DataList1" runat="server" Width="627px" >
    <ItemTemplate>
    <div id="selector2">
    <div id="div1" style="padding-left:5px;">
    <asp:Label ID="label1" runat="server"  Text='<%# DataBinder.Eval(Container.DataItem, "SE_eventname")%>' ForeColor="#0099CC" Font-Bold="true" Font-Size="Medium"></asp:Label>
    </div>
    <div id="div2" align="center">
    <asp:TextBox ID="txt1" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "SE_eventdetails")%>' Style="overflow: hidden;resize:none;" Height="30px" TextMode="MultiLine" Width="95%" MaxLength="100" BorderStyle="None" ></asp:TextBox>
    </div>
    <div id="div3" align="right" style="padding-right:5px;">
        <asp:LinkButton ID="LinkButton1" CommandName="view" runat="server">View more</asp:LinkButton>
    </div>
    </div>
    <asp:Button ID="hiddenbutton" Visible="false" Text='<%# DataBinder.Eval(Container.DataItem, "SE_postid")%>' runat="server"/>
    <br />
    </ItemTemplate>
     <AlternatingItemStyle BackColor="White" />

    <ItemStyle BackColor="#FFFBD6" ForeColor="#333333"/>

    <SelectedItemStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
 
    </asp:DataList>
    <div id="div4" align="center">
  <table>
    <tr>
    <td colspan="5">  </td>
    </tr>
    <tr>
    <td width="80" valign="top" align="center"><asp:LinkButton ID="lnkFirst"
            runat="server" onclick="lnkFirst_Click">First</asp:LinkButton></td>
    <td width="80" valign="top" align="center"><asp:LinkButton ID="lnkPrevious"
            runat="server" onclick="lnkPrevious_Click">Previous</asp:LinkButton></td>
    <td>
            <asp:DataList ID="DataListPaging" runat="server" RepeatDirection="Horizontal"
                onitemcommand="DataListPaging_ItemCommand"
                onitemdatabound="DataListPaging_ItemDataBound">
            <ItemTemplate>
                <asp:LinkButton ID="Pagingbtn" runat="server" CommandArgument='<%# Eval("PageIndex") %>' CommandName="newpage" Text='<%# Eval("PageText") %> '></asp:LinkButton>
            </ItemTemplate>
            </asp:DataList>
    </td>
    <td width="80" valign="top" align="center">
            <asp:LinkButton ID="lnkNext" runat="server" onclick="lnkNext_Click">Next</asp:LinkButton>
    </td>
    <td width="80" valign="top" align="center">
        <asp:LinkButton ID="lnkLast" runat="server" onclick="lnkLast_Click">Last</asp:LinkButton>
    </td>
    </tr>
    <tr>
    <td colspan="5" align="center"><asp:Label ID="lblpage" runat="server" Text=""></asp:Label></td></tr>
    </table>    
</div>

<%--<asp:DataList ID="DataList1" runat="server" Width="150px">
    <ItemTemplate>
<table width="200px" height="300px" border="1">
<tr>
<td> Eventname:<asp:Label ID="label1" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "SE_eventname")%>'></asp:Label></td>
</tr>
<tr>
<td> Eventdetails:<asp:Label ID="label2" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "SE_eventdetails")%>'></asp:Label></td>
</tr>
</table>
</ItemTemplate>
    </asp:DataList>--%>
    </div>
...............................................................


......................................................................

and your code behind should contain this:


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.Data.SqlClient;

public partial class Events : System.Web.UI.Page
{


    PagedDataSource pgsource = new PagedDataSource();
    int findex, lindex;
    DataRow dr;

    protected void Page_Load(object sender, EventArgs e)
    {
        //During first time page load this method call
        if (!Page.IsPostBack)
        {
            BindDataList();
            LoadDDL();
        }
    }

    public DataTable getTheData()
    {

        string connstr = ConfigurationManager.ConnectionStrings["smartedu"].ConnectionString;
        SqlConnection con = new SqlConnection(connstr);
        con.Open();


        SqlDataAdapter objSQLAdapter = new SqlDataAdapter("select * from Events", con);

        DataSet DS = new DataSet();

        objSQLAdapter.Fill(DS);

        con.Close();
        if (DS.Tables[0].Rows.Count == 0)
        {

            //lbl_msg.Text = "";

            DataList1.Visible = false;

        }

        else
        {

            Session["cnt"] = DS.Tables[0].Rows.Count;

        }

        return DS.Tables[0];

    }

    private void BindDataList()
    {
        //Create new DataTable dt
        DataTable dt = getTheData();
        pgsource.DataSource = dt.DefaultView;

        //Set PageDataSource paging
        pgsource.AllowPaging = true;

        //Set number of items to be displayed in the DataList using drop down list
        if (ddlIndex.SelectedIndex == -1 || ddlIndex.SelectedIndex == 0)
        {
            pgsource.PageSize = 10;
        }
        else
        {
            pgsource.PageSize = Convert.ToInt32(ddlIndex.SelectedItem.Value);
        }


        //Get Current Page Index
        pgsource.CurrentPageIndex = CurrentPage;

        //Store it Total pages value in View state
        ViewState["totpage"] = pgsource.PageCount;

        //Below line is used to show page number based on selection like "Page 1 of 20"
        lblpage.Text = "Page " + (CurrentPage + 1) + " of " + pgsource.PageCount;

        //Enabled true Link button previous when current page is not equal first page
        //Enabled false Link button previous when current page is first page
        lnkPrevious.Enabled = !pgsource.IsFirstPage;

        //Enabled true Link button Next when current page is not equal last page
        //Enabled false Link button Next when current page is last page
        lnkNext.Enabled = !pgsource.IsLastPage;

        //Enabled true Link button First when current page is not equal first page
        //Enabled false Link button First when current page is first page
        lnkFirst.Enabled = !pgsource.IsFirstPage;

        //Enabled true Link button Last when current page is not equal last page
        //Enabled false Link button Last when current page is last page
        lnkLast.Enabled = !pgsource.IsLastPage;

        //Bind resulted PageSource into the DataList
        DataList1.DataSource = pgsource;
        DataList1.DataBind();

        //Create Paging in the second DataList "DataListPaging"
        doPaging();
    }

    private void doPaging()
    {
        DataTable dt = new DataTable();
        //Add two column into the DataTable "dt"
        //First Column store page index default it start from "0"
        //Second Column store page index default it start from "1"
        dt.Columns.Add("PageIndex");
        dt.Columns.Add("PageText");

        //Assign First Index starts from which number in paging data list
        findex = CurrentPage - 5;

        //Set Last index value if current page less than 5 then last index added "5" values to the Current page else it set "10" for last page number
        if (CurrentPage > 5)
        {
            lindex = CurrentPage + 5;
        }
        else
        {
            lindex = 10;
        }

        //Check last page is greater than total page then reduced it to total no. of page is last index
        if (lindex > Convert.ToInt32(ViewState["totpage"]))
        {
            lindex = Convert.ToInt32(ViewState["totpage"]);
            findex = lindex - 10;
        }

        if (findex < 0)
        {
            findex = 0;
        }

        //Now creating page number based on above first and last page index
        for (int i = findex; i < lindex; i++)
        {
            DataRow dr = dt.NewRow();
            dr[0] = i;
            dr[1] = i + 1;
            dt.Rows.Add(dr);
        }

        //Finally bind it page numbers in to the Paging DataList
        DataListPaging.DataSource = dt;
        DataListPaging.DataBind();
    }

    private int CurrentPage
    {
        get
        {   //Check view state is null if null then return current index value as "0" else return specific page viewstate value
            if (ViewState["CurrentPage"] == null)
            {
                return 0;
            }
            else
            {
                return ((int)ViewState["CurrentPage"]);
            }
        }
        set
        {
            //Set View statevalue when page is changed through Paging DataList
            ViewState["CurrentPage"] = value;
        }
    }

    protected void DataListPaging_ItemCommand(object source, DataListCommandEventArgs e)
    {
        if (e.CommandName.Equals("newpage"))
        {
            //Assign CurrentPage number when user click on the page number in the Paging DataList
            CurrentPage = Convert.ToInt32(e.CommandArgument.ToString());
            //Refresh DataList "DlistEmp" Data once user change page
            BindDataList();
        }
    }

    protected void lnkFirst_Click(object sender, EventArgs e)
    {
        //If user click First Link button assign current index as Zero "0" then refresh DataList "DlistEmp" Data.
        CurrentPage = 0;
        BindDataList();
    }

    protected void lnkLast_Click(object sender, EventArgs e)
    {
        //If user click Last Link button assign current index as totalpage then refresh DataList "DlistEmp" Data.
        CurrentPage = (Convert.ToInt32(ViewState["totpage"]) - 1);
        BindDataList();
    }

    protected void lnkPrevious_Click(object sender, EventArgs e)
    {
        //If user click Previous Link button assign current index as -1 it reduce existing page index.
        CurrentPage -= 1;
        //refresh DataList "DlistEmp" Data
        BindDataList();
    }

    protected void lnkNext_Click(object sender, EventArgs e)
    {
        //If user click Next Link button assign current index as +1 it add one value to existing page index.
        CurrentPage += 1;

        //refresh DataList "DlistEmp" Data
        BindDataList();
    }

    void LoadDDL()
    {
        //Below code is used to bind values in the drop down list
        for (int i = 1; i <= 10; i++)
        {
            ddlIndex.Items.Add(i.ToString());
        }
        ddlIndex.Items.Insert(0, new ListItem("--Select--", "--Select--"));
    }

    protected void ddlIndex_SelectedIndexChanged(object sender, EventArgs e)
    {
        //Set Default current index Zero default and refresh it page size based on Drop Down List selected
        CurrentPage = 0;
        BindDataList();
    }
    protected void DataListPaging_ItemDataBound(object sender, DataListItemEventArgs e)
    {
        //Enabled False for current selected Page index
        LinkButton lnkPage = (LinkButton)e.Item.FindControl("Pagingbtn");
        if (lnkPage.CommandArgument.ToString() == CurrentPage.ToString())
        {
            lnkPage.Enabled = false;
        }
    }

}


.....................................................................



finished...............................!

Wednesday 11 January 2012

Datapaging with datalist

first in design page:



    <asp:Label ID="error" runat="server" Text=""></asp:Label>
<div id="selector1" style="font-family:Tahoma;
      font-size:15px;
      font-weight:bold">
 &nbsp;&nbsp;&nbsp;Events and Exhibitions
</div>
<div id="selector" align="center" >
    <asp:DataList ID="DataList1" runat="server" Width="627px" >
    <ItemTemplate>
    <div id="selector2">
    <div id="div1" style="padding-left:5px;">
    <asp:Label ID="label1" runat="server"  Text='<%# DataBinder.Eval(Container.DataItem, "SE_eventname")%>' ForeColor="#0099CC" Font-Bold="true" Font-Size="Medium"></asp:Label>
    </div>
    <div id="div2" align="center">
    <asp:TextBox ID="txt1" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "SE_eventdetails")%>' Style="overflow: hidden;resize:none;" Height="30px" TextMode="MultiLine" Width="95%" MaxLength="100" BorderStyle="None" ></asp:TextBox>
    </div>
    <div id="div3" align="right" style="padding-right:5px;">
        <asp:LinkButton ID="LinkButton1" runat="server">View more</asp:LinkButton>
    </div>
    </div>
    <br />
    </ItemTemplate>
 
    <AlternatingItemStyle BackColor="White" />

    <ItemStyle BackColor="#FFFBD6" ForeColor="#333333"/>

    <SelectedItemStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
    </asp:DataList>
    <div id="div4" align="right">
    <asp:LinkButton ID="btn_prev" runat="server" onclick="btn_prev_Click">Prev</asp:LinkButton>

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

<asp:LinkButton ID="btn_first" runat="server" onclick="btn_first_Click">First</asp:LinkButton>

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

<asp:LinkButton ID="btn_nxt" runat="server" onclick="btn_nxt_Click">Next</asp:LinkButton>

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

<asp:LinkButton ID="btn_last" runat="server" onclick="btn_last_Click">Last</asp:LinkButton>
    </div>
</div>



..............................................................................
this is how your Design page looks:

................................................

and your code file should contain this:


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.Data.SqlClient;

public partial class check : System.Web.UI.Page
{
    decimal count; //for count the total records.

    Decimal last1; // to access the last record

    String fn; // for image name

    String pth; // for storing the path

    string connstr = ConfigurationManager.ConnectionStrings["your connection string"].ConnectionString;

 

    SqlCommand cmd;


    PagedDataSource pageData = new PagedDataSource();


    protected void Page_Load(object sender, EventArgs e)
    {
 
        SqlConnection con = new SqlConnection(connstr);
        con.Open();

        doPaging();
    }

 
    public DataTable getTheData()
    {
        SqlConnection con = new SqlConnection(connstr);
        con.Open();


                    SqlDataAdapter objSQLAdapter = new SqlDataAdapter("select SE_eventname,SE_eventdetails from Events", con);

                    DataSet DS = new DataSet();

                    objSQLAdapter.Fill(DS);

                    if (DS.Tables[0].Rows.Count == 0)

                    {

                    //lbl_msg.Text = "";

                    DataList1.Visible = false;

                    }

                    else

                    {

                    Session["cnt"] = DS.Tables[0].Rows.Count;

                    }

                    return DS.Tables[0];

        }


    private void doPaging()
    {

        //paging function

        try
        {

            pageData.DataSource = getTheData().DefaultView; //will call the getTheData() method

            pageData.AllowPaging = true;

            pageData.PageSize = 2;

            count = Convert.ToInt32(Session["cnt"]);

            last1 = count / pageData.PageSize;

            last1 = Convert.ToDecimal(Math.Ceiling(last1)); // will convert the 17/4 = 4.5 –> 5 pages

            try
            {

                pageData.CurrentPageIndex = Int32.Parse(Request["page"].ToString());

            }

            catch
            {

                pageData.CurrentPageIndex = 0; // default first 4 images

            }

            btn_prev.Visible = (!pageData.IsFirstPage);

            btn_first.Visible = (!pageData.IsFirstPage);

            btn_nxt.Visible = (!pageData.IsLastPage);

            btn_last.Visible = (!pageData.IsLastPage);



            DataList1.DataSource = pageData;

            DataList1.DataBind();

        }

        catch
        {

        }

    }
       

           protected void btn_prev_Click(object sender, EventArgs e)

                    {

                    Response.Redirect(Request.CurrentExecutionFilePath + "?Page=" + (pageData.CurrentPageIndex -1).ToString());

                    }

                    protected void btn_first_Click(object sender, EventArgs e)

                    {

                    Response.Redirect(Request.CurrentExecutionFilePath + "?Page=" + (pageData.CurrentPageIndex == 1).ToString());

                    }

                    protected void btn_nxt_Click(object sender, EventArgs e)

                    {

                    Response.Redirect(Request.CurrentExecutionFilePath + "?Page=" + (pageData.CurrentPageIndex + 1).ToString());

                    }

                    protected void btn_last_Click(object sender, EventArgs e)

                    {

                    Response.Redirect("check.aspx?page=" + Convert.ToInt32(last1 - 1)); // dtlist.aspx to access the last record.


                    }


}


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


and your final output is:




Thats it......! u r done with paging


Tuesday 10 January 2012

Simple css to center aligning the text in the div tag

<head>

<style type="text/css">

.word
{
font-size: 13px;
font-family: Arial,Helvetica,Sans-Serif;
font-style: normal;font-weight: normal;
}

<style>
</head>
.......................................................

<body>


<div class="word">
<div align=justify>standardized test of reading and verbal reasoning skills designed by the USA based Law School Admission Council (LSAC) for use by law schools in India. LSAT 2012 on Saturday 5th May , 2012 at any of the test centres spread across 15 cities in India. The test will be administered in a paper and pencil format in India and in computer-based testing (CBT) mode at overseas locations. Registration Fee – Rs. 3500/- The demand draft/pay order/banker's cheque should reach the below mentioned address on or before 12th April, 2012 either by post or courier. Pearson VUE 6708, DLF Phase IV, Gurgaon-122002, Haryana,India
</div>
</div>

</body>

Result:










Thursday 5 January 2012

simple css to grow the size of the div tag according to the inner content



 <style type="text/css">
your div tag
     {
             border:1px solid #CACACA ;
             overflow:auto;
             min-height:480px;
       
     }

 </style>