Drop Down MenusCSS Drop Down MenuPure CSS Dropdown Menu

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();
                   

                }
            
            
            }

        }
    }
}