Drop Down MenusCSS Drop Down MenuPure CSS Dropdown Menu

Friday, 22 November 2013

File Upload , Display in Gridview, and finally bulk insert into Database

TRICK 1 -->

---------------------------Excel-----------




--------------------------------------------------------------
SQL

























-----ASPX--
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication4._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>
    <title>Read and Display Data From an Excel File (.xsl or .xlsx) in ASP.NET</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <b>Please Select Excel File: </b>
        <asp:FileUpload ID="fileuploadExcel" runat="server" />&nbsp;&nbsp;
        <asp:Button ID="btnImport" runat="server" Text="Import Data" OnClick="btnImport_Click" />
        <asp:Button ID="btnsql" runat="server" Text="Bulk Insert" 
            OnClick="btn_import_sql" />
        <br />
        <asp:Label ID="lblMessage" runat="server" Visible="False" Font-Bold="True" ForeColor="#009933"></asp:Label>
        <br />
        <asp:Label ID="Label1" runat="server" Visible="true" Font-Bold="True" ForeColor="#009933"></asp:Label>
        <asp:GridView ID="grvExcelData" runat="server">
            <HeaderStyle BackColor="#df5015" Font-Bold="true" ForeColor="White" />
        </asp:GridView>
    </div>
    </form>
</body>
</html>










------------.CS-----------



using System;
using System.Data;
using System.Data.OleDb;
using System.IO;
using System.Data.SqlClient;
using System.Configuration;
using System.Text;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;

namespace WebApplication4
{
    public partial class _Default : System.Web.UI.Page
    {
        string str;

        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void btnImport_Click(object sender, EventArgs e)
        {
            string connString = "";
            string strFileType = Path.GetExtension(fileuploadExcel.FileName).ToLower();
            string path = fileuploadExcel.PostedFile.FileName;
            //Connection String to Excel Workbook
            if (strFileType.Trim() == ".xls")
            {
                connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
            }
            else if (strFileType.Trim() == ".xlsx")
            {
                connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
            }
            string query = "SELECT ltrim(rtrim([userid])),[starttime],[endtime] FROM [Sheet1$]";
            OleDbConnection conn = new OleDbConnection(connString);
            if (conn.State == ConnectionState.Closed)
                conn.Open();
            OleDbCommand cmd = new OleDbCommand(query, conn);
            OleDbDataAdapter da = new OleDbDataAdapter(cmd);
            DataSet ds = new DataSet();
            da.Fill(ds);
            grvExcelData.DataSource = ds.Tables[0];
            grvExcelData.DataBind();
            da.Dispose();
            conn.Close();
            conn.Dispose();
        }

        protected void btn_import_sql(object sender, EventArgs e)
        {
               string strcon = ConfigurationManager.ConnectionStrings["ConnectionStringdb"].ConnectionString;
               using (SqlConnection con = new SqlConnection(strcon))
               {

                   for (int i = 0; i < grvExcelData.Rows.Count; i++)
                   { 
                   GridViewRow  row = grvExcelData.Rows[i];
                   con.Open();
                   str= "insert into temp_adhoc_arihant2(userid,starttime,endtime)values('"+ row.Cells[0].Text +"','"+ row.Cells[1].Text +"','"+ row.Cells[2].Text +"')";

                   SqlCommand com = new SqlCommand(str, con);
                   com.ExecuteNonQuery();
                   con.Close();

                   }
                   Label1.Text = "Records successfully inserted";

               }
        }

    }
}














-------If you hit bulk insert--


 --database table-->












---Will come up with trick2 and trick3 for bulk insert....

--If it helped you ...kindly give feedback :)







Monday, 18 November 2013

Display GridData detail on mouse over


















----------------------------FUNCTION TO GET THE HTML FOR TOOL TIP---------------------------

USE [anurag]
GO
/****** Object:  UserDefinedFunction [dbo].[testfunction]    Script Date: 11/13/2013 23:56:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER function [dbo].[testfunction]-- 1
(
@id int
)
RETURNS VARCHAR(max)           
AS           
BEGIN 
declare @detail table
(
total int identity(1,1) not null,
id int,
detail varchar(50)
)  

DECLARE @HTML NVARCHAR(max)
DECLARE @HTMLHEADER NVARCHAR(max)          
DECLARE @HTMLFOOTER NVARCHAR(max)            
DECLARE @HTMLROWS



 NVARCHAR(max) 
DECLARE @i Int,@MaxI Int,@MyRowCount Int,@id1 int,@details varchar(50)
set @HTMLROWS='' 


if(@id is not null and len(@id) > 0)
  begin   
       set @HTMLHEADER='<STRONG></STRONG><Table width=150>'      
       set @HTMLFOOTER='</Table>'  

 insert into @detail(id,detail)
 select id,place from Places where id=@id

  SELECT  @MaxI=@@RowCount,@i = 1
   
  IF(@MaxI=0) 
  Begin
  set @HTMLROWS=@HTMLROWS +'<tr><td>'+'No places'
  end
  
  else
           begin
  while @i <=@MaxI
  begin
  select @id1=id,@details=detail from @detail WHERE total = @i 
  set @HTMLROWS=
  @HTMLROWS +'<tr style=background-color:#808080;><td>' + 
  CAST(@i AS VARCHAR(10))+ '-->' + cast(@details as varchar(50))+ '<hr><span style=background-color:white;font-weight:bold</span></hr>' + '</td></tr>'
  SELECT  @i = @i + 1,
  @id = null
  end
  end

END
set @HTML= @HTMLHEADER +@HTMLROWS + @HTMLFOOTER            
      
   
RETURN @HTML
      
END          

<-----------------------------------------O/P OF FUNCTION------------------------------------------------->

--select [dbo].[testfunction](1) 

<STRONG></STRONG>
<Table width=150>

<tr style=background-color:#808080;>
<td>1-->Thoraipakkam
<hr><span style=background-color:white;font-weight:bold</span></hr>

</td></tr><tr style=background-color:#808080;>
<td>2-->Chrompet<hr><span style=background-color:white;font-weight:bold</span></hr>

</td></tr><tr style=background-color:#808080;><td>
3-->Shollinganallur<hr><span style=background-color:white;font-weight:bold</span></hr>

</td></tr><tr style=background-color:#808080;>
<td>4-->Perungudi<hr><span style=background-color:white;font-weight:bold</span></hr>
</td>

</tr>

</Table>

---------------------------------------------Stored Procedure----------------------------------

USE [anurag]
GO
/****** Object:  StoredProcedure [dbo].[Distanceprocedure]    Script Date: 11/13/2013 23:44:25 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER proc [dbo].[Distanceprocedure]
as
begin

select id,name,dbo.[testfunction](city.id) as functionhtml from city

end

---------------------------------------------.ASPX---------------------------------------------------------------------


<%@ 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">

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>

<script type="text/javascript" src="http://cdn.jsdelivr.net/jquery.simpletip/1.3.1/jquery.simpletip-1.3.1.min.js.txt"></script>

<script type="text/javascript">
    $(function() {
        $('[id*=GridView1] tr').each(function() {
            var toolTip = $(this).attr("title");
            $(this).find("td").each(function() {
                $(this).simpletip(
                    {
                        content: toolTip
                    });

            });
            $(this).removeAttr("title");
        });
    });
</script>

<style type="text/css">
    #GridView1 tr.rowHover:hover
    {
        background-color: green;
        font-family: Arial;
    }
</style>
<style type="text/css">
    .tooltip
    {
        position: absolute;
        top: 0;
        left: 0;
        z-index: 3;
        display: none;
        background-color: #FB66AA;
        color: White;
        padding: 2px;
        font-size: 10pt;
        font-family: Arial;
        width: 150PX;
    }
    td
    {
        cursor: pointer;
    }
</style>
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server" DataKeyNames="id" AutoGenerateColumns="False"
            Width="59%" OnRowDataBound="Gridplace_RowDataBound" BackColor="CadetBlue" BorderColor="Black"
            RowStyle-CssClass="rowHover">
            <Columns>
                <asp:TemplateField HeaderText="City" HeaderStyle-HorizontalAlign="Left" HeaderStyle-BackColor="GreenYellow">
                    <ItemTemplate>
                        <asp:Label ID="lblID" Font-Bold="true" BorderColor="CadetBlue" BorderStyle="Solid"
                            Font-Size="Medium" runat="server" Text='<%#Eval("id") %>' Width="283px"></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Place" HeaderStyle-HorizontalAlign="Left" HeaderStyle-BackColor="GreenYellow">
                    <ItemTemplate>
                        <asp:Label ID="lblName" Font-Bold="true" BorderColor="CadetBlue" BorderStyle="Solid"
                            Font-Size="Medium" runat="server" Text='<%#Eval("name") %>' Width="283px"></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:Label ID="lblfunction" Font-Bold="true" Visible="false" BorderColor="CadetBlue"
                            BorderStyle="Solid" Font-Size="Medium" runat="server" Text='<%#Bind("functionhtml") %>'
                            ></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
    </div>
    </form>
</body>
</html>

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

        if (!IsPostBack)
        {

            string strcon = ConfigurationManager.ConnectionStrings["ConnectionStringdb"].ConnectionString;
            using (SqlConnection con = new SqlConnection(strcon))
            {

                SqlCommand cmd = new SqlCommand("Distanceprocedure", con);
                cmd.CommandType = CommandType.StoredProcedure;

                con.Open();
                GridView1.DataSource = cmd.ExecuteReader();
                GridView1.DataBind();
                con.Close();
            }


        }
    }

    protected void Gridplace_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {

            e.Row.ToolTip = DataBinder.Eval(e.Row.DataItem, "functionhtml").ToString();
            ////e.Row.ToolTip = functionhtml;

            //e.Row.ToolTip = (e.Row.DataItem as DataRowView)["functionhtml"].ToString();
            
        }
    }
}

-------------------------------------------------------O/P-----------------------------------------------------









Sunday, 10 November 2013

Multiply two columns in gridview


Backend :























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.Text;

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

            string strcon = ConfigurationManager.ConnectionStrings["ConnectionStringdb"].ConnectionString;
            using (SqlConnection con = new SqlConnection(strcon))
            {

                SqlCommand cmd = new SqlCommand("USP_datamanipulation", con);
                cmd.CommandType = CommandType.StoredProcedure;

                con.Open();
                GridView1.DataSource = cmd.ExecuteReader();
                GridView1.DataBind();
                con.Close();
            }


        }
    }
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {


        for (int i = 0; i < GridView1.Rows.Count; i++)
        {
       
            GridView1.Rows[i].Cells[3].Text = Convert.ToString(Convert.ToDecimal(GridView1.Rows[i].Cells[1].Text) * Convert.ToDecimal(GridView1.Rows[i].Cells[2].Text));

        }

    }
}


o/p














Tuesday, 29 October 2013

Enable view state made false...see the difference


<--------------------------Enable View State is Made on------------------------------------------------>
<--------------------------------------------------------------------------------------------------------->
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;


public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.IsPostBack)
        {

            Getdata();
       
        }
    }

        private void Getdata()
        {
       
           string strcon= ConfigurationManager.ConnectionStrings["ConnectionStringdb"].ConnectionString;

            using(SqlConnection con= new SqlConnection(strcon))
            {
                con.Open();
                SqlCommand cmd= new SqlCommand("emp",con);
                cmd.CommandType= CommandType.StoredProcedure;
                GridView1.DataSource=cmd.ExecuteReader();
                GridView1.DataBind();
                con.Close();
           
            }
       
       
        }
    }
//if you hit the button the next time....the gridview displays the data....





<-------------------------------Enable View State is Made off-------------------------------------------->
<--------------------------------------------------------------------------------------------------------->


If you hit button ...then no grid
If you hit f5...its pageload...so grid displays





--Webconfig
<connectionStrings>
<add name="ConnectionStringdb" connectionString="Data Source=X.X.X.X;          Initial Catalog=anurag;          Integrated Security=True;" providerName="System.Data.SqlClient"/>
</connectionStrings>


sql


create table employees
(
name varchar(40),
age int,
sex varchar(30)
)

insert into employees
select 'anurag',24,'m'
union all select 'anurag',24,'m'
union all select 'abhishek',22,'m'
union all select 'ruchi',23,'f'

select * from employees

alter procedure emp
as
begin
select * from employees
end



Friday, 25 October 2013

GRIDVIEW + JAVASCRIPT

The basic concept behind this is when the GridView is rendered on the client machine it is rendered as a simple HTML table. Hence what the JavaScript will see a HTML table and not the ASP.Net GridView control.

Thursday, 24 October 2013

VIEW STATE AND PRERENDER



STEP 1

using System;

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.Collections;

public partial class _Default : System.Web.UI.Page

{

 ArrayList PageArrayList;

 ArrayList CreateArray()

 {

 // Create a sample ArrayList.

 ArrayList result = new ArrayList(4);

 result.Add("item 1");

 result.Add("item 2");

 result.Add("item 3");

 result.Add("item 4");

 return result;

 }

 protected void Page_Load(object sender, EventArgs e)

 {

 if (ViewState["arrayListInViewState"] != null)

 {

 PageArrayList = (ArrayList)ViewState["arrayListInViewState"];

 }

 else

 {

 // ArrayList isn't in view state, so it must be created and

populated.

 PageArrayList = CreateArray();

 gridview1.DataSource = PageArrayList;

 gridview1.DataBind();

 }

 // Code that uses PageArrayList.

 }

 void Page_PreRender(object sender, EventArgs e)

 {

 // Save PageArrayList before the page is rendered.

 ViewState.Add("arrayListInViewState", PageArrayList);

 }

 protected void Button1_Click(object sender, EventArgs e)

 {

 PageArrayList.Add("item6");

 PageArrayList.Add("item7");

 PageArrayList.Add("item8");

 PageArrayList.Add("item9");

 gridview2.DataSource = PageArrayList;

 gridview2.DataBind();

 }

}

--WHEN PAGE LOADS
































viewstate["abc"]=pagearraylist;
viewstate.add("","");

--both are same

Wednesday, 23 October 2013

Populate data in gridview using datatable[SELECT,EDIT,UPDATE,CANCEL]





using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

public partial class _Default : System.Web.UI.Page
{
 
 
 
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.IsPostBack)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("Name");
            dt.Columns.Add("Age");
            dt.Columns.Add("Sex");

            dt.Rows.Add("Anurag", "24", "M");
            dt.Rows.Add("Ruchi", "23", "F");
            dt.Rows.Add("Abhi", "22", "M");

            GridView1.DataSource = dt;
            GridView1.DataBind();

        }
    }


    protected void Button1_Click(object sender, EventArgs e)
    {

    }
}













-------------------------------------SELECT IN GRID VIEW-------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

public partial class _Default : System.Web.UI.Page
{
 
 
 
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.IsPostBack)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("Name");
            dt.Columns.Add("Age");
            dt.Columns.Add("Sex");

            dt.Rows.Add("Anurag", "24", "M");
            dt.Rows.Add("Ruchi", "23", "F");
            dt.Rows.Add("Abhi", "22", "M");

            GridView1.DataSource = dt;
            GridView1.DataBind();

        }
    }


    protected void Button1_Click(object sender, EventArgs e)
    {

    }
    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {

    }
    protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {

    }
    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {

    }
    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "Select")
        {

            int num = Convert.ToInt32(e.CommandArgument);

            TextName.Text= GridView1.Rows[num].Cells[2].Text;
            TextAge.Text=  GridView1.Rows[num].Cells[3].Text;
            TextSex.Text = GridView1.Rows[num].Cells[4].Text;
     
        }
    }
}

--SECOND ROW SELECTED




















----------------------------EDIT/UPDATE/CANCEL----------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

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

    public DataTable dtviewstate
    {

        get
        {
            return (DataTable)ViewState["dtview"];
        }

        set
       
        {

            ViewState["dtview"] = value;
        }
 
   
    }
   
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.IsPostBack)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("Name");
            dt.Columns.Add("Age");
            dt.Columns.Add("Sex");

            dt.Rows.Add("Anurag", "24", "M");
            dt.Rows.Add("Ruchi", "23", "F");
            dt.Rows.Add("Abhi", "22", "M");

            dtviewstate = dt;
            GridView1.DataSource = dt;
            GridView1.DataBind();

        }
    }


    protected void Button1_Click(object sender, EventArgs e)
    {

    }
    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        GridView1.EditIndex = e.NewEditIndex;
        HiddenField1.Value = e.NewEditIndex.ToString();
        GridView1.DataSource = dtviewstate;
        GridView1.DataBind();

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

    }
    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        TextBox t1 = new TextBox();
        TextBox t2 = new TextBox();
        TextBox t3 = new TextBox();

        t1 = (TextBox)GridView1.Rows[Convert.ToInt32( HiddenField1.Value)].Cells[2].Controls[0];
        t2 = (TextBox)GridView1.Rows[Convert.ToInt32(HiddenField1.Value)].Cells[3].Controls[0];
        t3 = (TextBox)GridView1.Rows[Convert.ToInt32(HiddenField1.Value)].Cells[4].Controls[0];


        dtviewstate.Rows[e.RowIndex]["Name"]=t1.Text;
        dtviewstate.Rows[e.RowIndex]["Age"]=t2.Text;
        dtviewstate.Rows[e.RowIndex]["Sex"]=t3.Text;

        GridView1.EditIndex = -1;
        GridView1.DataSource = dtviewstate;
        GridView1.DataBind();
   
   
   
   
    }
    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "Select")
        {

            int num = Convert.ToInt32(e.CommandArgument);

            TextName.Text = GridView1.Rows[num].Cells[2].Text;
            TextAge.Text=  GridView1.Rows[num].Cells[3].Text;
            TextSex.Text = GridView1.Rows[num].Cells[4].Text;
       
        }
    }
}






Tuesday, 22 October 2013

Session in Asp.Net

Http Protocol is stateless protocol.

View state is accessible only with in same page[we have already seen]
Session variables can be accessed across pages.

Session is private to the users.  Actual data get stored on server.
Next things is how does server identifies whose data is whose.
If data is stored in the server and the server uses http protocol ...then server doesnt knows whose data is whose.

Asp.net has taken care of it. For every user it has create  a key.
Asp.net stores all the information of session variables in the server but then it sends the key to the browser or the end user who is surfing the site. And the key is stored as the cookies file. Cookie is nothing but simple text file which is created in the browser folder.
So session data is stored on the server and keys are stored in cookies files.
If cookie is disabled then sesssion id key is passed via query string.


1)The session state is used to maintain state value in the server machine.
   The session state maintains the values in the session object memory.

2) 20 Min by default.

you can extend it to 1000 min...





























-----------------------------------------------default.aspx---------------------------------------------------------


<%@ 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></title>
</head>
<body>
    <form id="form1" runat="server">
    UserName&nbsp;
    <asp:TextBox ID="txtname" runat="server" style="margin-right: 0px"></asp:TextBox>
    <br />
    Password&nbsp;&nbsp;&nbsp;
    <asp:TextBox ID="txtpassword" runat="server"  
        style="margin-left: 0px; margin-bottom: 0px"></asp:TextBox>
    &nbsp;
    <br />
    <br />
    <asp:Button ID="Button1" runat="server" Text="Sign In" 
        onclick="Button1_Click" />
    </form>
</body>
</html>




---------------------------------------------default.cs---------------------------------------------

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

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

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

        if (txtname.Text == "anurag" && txtpassword.Text == "123")
        {

                Session["abc"] = txtname.Text;
            Session.Timeout = 1;
            Response.Redirect("~/Default2.aspx");
        }
        else 
        {

            Response.Write("wrong username or password");
            txtname.Text ="";
            txtpassword.Text ="";

        }
        

    }
}

------------default2.aspx design-------------------------------------------------------------------------









-------------------------------------------default2.aspx------------------------------------------

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



<!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>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
    
        Hello Welcome To Our Site
        <asp:Label ID="Label1" runat="server"></asp:Label>
    
    
    </div>
    <asp:Button ID="Button1" runat="server" onclick="Button1_Click" 
        Text="signout" />
    </form>
</body>
</html>



--------------------------------------------default2.cs-------------------------------------------------


using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Default2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["abc"] == null)
        {

            Response.Redirect("~/Default.aspx");

        }
        else
        {
            Label1.Text = Session["abc"].ToString();

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

        Session.Remove("abc");
    //if you comment the above line then you can't log out

        if (Session["abc"] == null)
        {

            Response.Redirect("~/Default.aspx");

        }
    }
}

-------------------------------------------out put-------------------------------------------------------



















Monday, 21 October 2013

Events IN Asp.Net

Events can occur at 3 levels
1)Application level[Application start]
2)page level[Page Load]
3)control level[selected index of dropdownlist control,button click]

ViewState varible is used to preserve data across page postback.By default viewstate of one webform is not avaliable in other webform.

The following are the techniques that is used to send data from one webform to another webform.

1)cookies
2)Query string
3)Session state-->single user global data. For a given user
4)Application state-->multi user global data. Avaliable across all pages and across all sessions.

Session state variables are avaliable across all the pages,but only for a single session.

Tuesday, 8 October 2013

populate data in gridview tricks and tips and how stringbuilder is used to populate the data

--trick 1
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.Text;


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

            if (!IsPostBack)
            {

                string strcon = ConfigurationManager.ConnectionStrings["ConnectionStringdb"].ConnectionString;
                using (SqlConnection con = new SqlConnection(strcon))
                {
                 
                          string str = "select * from employee";
                    con.Open();
                    SqlCommand cmd = new SqlCommand(str, con);
                    SqlDataReader rdr = cmd.ExecuteReader();
                    GridView1.DataSource = rdr;
                    GridView1.DataBind();
                    con.Close();

                }
         
         
            }

        }
    }
}


--web config

<connectionStrings>
<add name="ConnectionStringdb" connectionString="Data Source=ANURAG-PC\SQLEXPRESS;Initial Catalog=anurag;Integrated Security=True;" providerName="System.Data.SqlClient"/>
</connectionStrings>


















---------------------trick 2-------------------------------------------------------------


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.Text.RegularExpressions;
using System.Text;





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

            if (!IsPostBack)
            {

                string strcon = ConfigurationManager.ConnectionStrings["ConnectionStringdb"].ConnectionString;
                using (SqlConnection con = new SqlConnection(strcon))
                {
             
               StringBuilder str = new StringBuilder();
          str.Append("select * from employee");
          str.Append(" where Name='anurag'");
                    con.Open();
                    SqlCommand cmd = new SqlCommand(str.ToString(), con);
                    SqlDataReader rdr = cmd.ExecuteReader();
                    GridView1.DataSource = rdr;
                    GridView1.DataBind();
                    con.Close();

                }
         
         
            }

        }
    }
}








----trick 3 using sqladapter


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.Text.RegularExpressions;
using System.Text;





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

            if (!IsPostBack)
            {

                string strcon = ConfigurationManager.ConnectionStrings["ConnectionStringdb"].ConnectionString;
                using (SqlConnection con = new SqlConnection(strcon))
                {
                 
                    StringBuilder str = new StringBuilder();
                    str.Append("select * from employee");
                    str.Append(" where Name='anurag'");
                    con.Open();
                    SqlCommand cmd = new SqlCommand(str.ToString(), con);
                         SqlDataAdapter adp = new SqlDataAdapter();
                    DataSet ds = new DataSet();
                    adp.SelectCommand = cmd;
                    adp.Fill(ds);
                    GridView1.DataSource = ds;
                    GridView1.DataBind();
                    con.Close();

                }
         
         
            }

        }
    }
}



--trick 4 slight change


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.Text.RegularExpressions;
using System.Text;





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

            if (!IsPostBack)
            {

                string strcon = ConfigurationManager.ConnectionStrings["ConnectionStringdb"].ConnectionString;
                using (SqlConnection con = new SqlConnection(strcon))
                {
                 
                    StringBuilder str = new StringBuilder();
                    str.Append("select * from employee");
                    str.Append(" where Name='anurag'");
                    con.Open();
                    SqlCommand cmd = new SqlCommand(str.ToString(), con);
                    SqlDataAdapter adp = new SqlDataAdapter();
                    DataSet ds = new DataSet();
                    adp.SelectCommand = cmd;
                    adp.Fill(ds);
                    DataTable dt = ds.Tables[0];
              GridView1.DataSource = dt;
                    GridView1.DataBind();
                    con.Close();

                }
         
         
            }

        }
    }
}



--trick 5--you can skip con.open and con.close when using sqladapter


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.Text.RegularExpressions;
using System.Text;





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

            if (!IsPostBack)
            {

                string strcon = ConfigurationManager.ConnectionStrings["ConnectionStringdb"].ConnectionString;
                using (SqlConnection con = new SqlConnection(strcon))
                {
                 
                    StringBuilder str = new StringBuilder();
                    str.Append("select * from employee");
                    str.Append(" where Name='anurag'");
               
//no con open and close. Disconnected architecture.....

                    SqlCommand cmd = new SqlCommand(str.ToString(), con);
                    SqlDataAdapter adp = new SqlDataAdapter();
                    DataSet ds = new DataSet();
                    adp.SelectCommand = cmd;
                    adp.Fill(ds);
                    DataTable dt = ds.Tables[0];
                    GridView1.DataSource = dt;
                    GridView1.DataBind();
                 

                }
         
         
            }

        }
    }
}




---trick 6 how to use listbox and display data in it


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.IO;
using System.Data;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
   
        datasetdemo();
       
    }
    
    private void datasetdemo()
    {
        string strsql = "select * from family where lastname like '%pat%'";

        try
        {
            using (SqlConnection cnn =
            new SqlConnection
            (@"Data Source=OMSHREERAM-PC\SQLEXPRESS;Initial Catalog=anurag;
                Integrated Security= True; "))
            {
                //SqlCommand cmd;
                using(SqlDataAdapter adp=new SqlDataAdapter(strsql,cnn))
                {
               
                DataSet ds= new DataSet();
                adp.Fill(ds,"anurag");

                foreach(DataRow dr in ds.Tables["anurag"].Rows)
                    {
                   
                    Lstbox.Items.Add(dr["lastname"].ToString());
                   
                    }
                    grd.DataSource = ds;
                    grd.DataBind();
               
                }
              

            }
        }
        catch(Exception ex)
        {
            errorlabel.Text = ex.Message;
       
        }
    }





























---------------------------slight change------------------------


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.IO;
using System.Data;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
   
        datasetdemo();
       
    }
    
    private void datasetdemo()
    {
        string strsql = "select * from family where lastname like '%pat%'";

        try
        {
            using (SqlConnection cnn =
            new SqlConnection
            (@"Data Source=OMSHREERAM-PC\SQLEXPRESS;Initial Catalog=anurag;
                Integrated Security= True; "))
            {
                //SqlCommand cmd;
                using(SqlDataAdapter adp=new SqlDataAdapter(strsql,cnn))
                {
               
                DataSet ds= new DataSet();
                adp.Fill(ds,"anurag");

                    //foreach(DataRow dr in ds.Tables["anurag"].Rows)
                    //{
                   
                    //Lstbox.Items.Add(dr["lastname"].ToString());
                   
                    //}

                     Lstbox.DataTextField = "lastname";
                 Lstbox.DataValueField = "personid";
                 Lstbox.DataSource = ds.Tables["anurag"];
                 Lstbox.DataBind();

                    grd.DataSource = ds;
                    grd.DataBind();
               
                }
              

            }
        }
        catch(Exception ex)
        {
            errorlabel.Text = ex.Message;
       
        }
    }
}


--same result


--Data column concept and trick


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.Text.RegularExpressions;
using System.Text;





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

            if (!IsPostBack)
            {

                string strcon = ConfigurationManager.ConnectionStrings["ConnectionStringdb"].ConnectionString;
                using (SqlConnection con = new SqlConnection(strcon))
                {
                    
                    StringBuilder str = new StringBuilder();
                    str.Append("select * from employee");
                    str.Append(" where Name='anurag'");
                  
                    SqlCommand cmd = new SqlCommand(str.ToString(), con);
                    SqlDataAdapter adp = new SqlDataAdapter();
                    DataSet ds = new DataSet();
                    adp.SelectCommand = cmd;
                    adp.Fill(ds,"anurag");


            foreach (DataColumn dc in ds.Tables["anurag"].Columns)
                    {

  ListBox1.Items.Add(string.Format("{0}:{1}", dc.ColumnName, dc.DataType));


                    }


                    DataTable dt = ds.Tables[0];
                    GridView1.DataSource = dt;
                    GridView1.DataBind();
                   

                }
            
            
            }

        }
    }
}