ViewState with example in asp.net C#

Thursday, December 30, 2010

How to select perticular column of gridview using asp.net C#

Step1: Add the gridview in your .aspx page.
<div>
    <asp:GridView ID="GridView1" runat="server"  AutoGenerateColumns="false"          
             DataKeyNames="EmpID"onrowcommand="GridView1_RowCommand">
          <Columns>
            <asp:BoundField DataField="EMPID" HeaderText="EmployeeID" />
         <asp:BoundField DataField="FirstName" HeaderText="FirstName" />
            <asp:BoundField DataField="LastName" HeaderText="LastName" />
            <asp:BoundField DataField="Address" HeaderText="Address" />
            <asp:BoundField DataField="Mobile" HeaderText="Mobile" />
            <asp:TemplateField>
            <ItemTemplate>
            <asp:Button ID="btnSelect" runat="server" Text="Select" CommandName="Select" CommandArgument='<%# Eval("Mobile") %>' />
            </ItemTemplate>
            </asp:TemplateField>
          </Columns>
        </asp:GridView>


        <asp:Label ID="lblMessage" runat="server"></asp:Label>   
    
        <asp:TextBox ID="txtMobile" runat="server"></asp:TextBox>
    </div>


step 2:- your .aspx.cs page.


NOTE:- this is my connection string which is using in below coding you can use your own to modify it in your web.config file.
My connectiion string is.
"

<connectionStrings>
    <add name="mycon" connectionString="data source=SHIVAMGUPTA; initial catalog=operation; integrated security=true;" providerName="System.Data.SqlClient"/>
  </connectionStrings>

"
**********************your code behind part.*********************

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


SqlConnection con;
    protected void Page_Load(object sender, EventArgs e)
    {
        string conection;
        conection = System.Configuration.ConfigurationManager.ConnectionStrings["mycon"].ConnectionString.ToString();
        con = new SqlConnection(conection);
        if (!IsPostBack)
        {
            FillGrid();
        }
    }




    protected void FillGrid()
    {
        SqlCommand cmd = new SqlCommand("select * from employee", con);
        con.Open();
        GridView1.DataSource = cmd.ExecuteReader();
        GridView1.DataBind();
        con.Close();
    }


    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "Select")
        {
            txtMobile.Text = Convert.ToString(e.CommandArgument);
            lblMessage.Text = "this the mobile no of selected row!";
        }
    }

}

Wednesday, December 29, 2010

Insert/Update/Delete in GridView using asp.net C#

Insert/Update/Delete in GridView using asp.net C#

Step1:-

Create a employee table:



CREATE TABLE EMPLOYEE
(
 EMPID INT IDENTITY(100,1),
 FIRSTNAME VARCHAR(20),
 LASTNAME VARCHAR(20),
 ADDRESS VARCHAR(100),
 MOBILE VARCHAR(20)
)


NOW INSERT SOME VALUES IN EMPLOYEE TABLE:


INSERT INTO EMPLOYEE(FIRSTNAME,LASTNAME,ADDRESS,MOBILE)VALUES('SHIVAM','GUPTA','NEW DELHI','8826743157')


STEP2:- CREATE CONNECTION STRING IN WEB.CONFIG FILE.



<connectionStrings>
    <add name="mycon" connectionString="data source=SHIVAMGUPTA; initial catalog=operation; integrated security=true;" providerName="System.Data.SqlClient"/>
  </connectionStrings>


STEP3:- TAKE A GRIDVIEW IN YOUR .ASPX PAGE.



<asp:GridView ID="GridView1" runat="server" AutoGenerateDeleteButton="true" AutoGenerateColumns="false"
            AutoGenerateEditButton="True" 
            onpageindexchanging="GridView1_PageIndexChanging" 
            onrowcancelingedit="GridView1_RowCancelingEdit"  DataKeyNames="EmpID"
            onrowdeleting="GridView1_RowDeleting" onrowediting="GridView1_RowEditing" 
            onrowupdating="GridView1_RowUpdating">
          <Columns>
            <asp:BoundField DataField="EMPID" HeaderText="EmployeeID" />
            <asp:BoundField DataField="FirstName" HeaderText="FirstName" />
            <asp:BoundField DataField="LastName" HeaderText="LastName" />
            <asp:BoundField DataField="Address" HeaderText="Address" />
            <asp:BoundField DataField="Mobile" HeaderText="Mobile" />
            
          </Columns>
        </asp:GridView>


        <asp:Label ID="lblMessage" runat="server"></asp:Label>






STEP4: NOW COME IN YOUR CODE BEHIND .ASPX.CS



public partial class _Default : System.Web.UI.Page
{
    SqlConnection con;
    protected void Page_Load(object sender, EventArgs e)
    {
        string conection;
        conection = System.Configuration.ConfigurationManager.ConnectionStrings["mycon"].ConnectionString.ToString();
         con = new SqlConnection(conection);
         if (!IsPostBack)
         {
             FillGrid();
         }


    }


    protected void FillGrid()
    {
      SqlCommand cmd = new SqlCommand("select * from employee", Con);
        con.Open();
        GridView1.DataSource = cmd.ExecuteReader();
        GridView1.DataBind();
        con.Close();
    }


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


    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        int index = GridView1.EditIndex;
        GridViewRow row = GridView1.Rows[index];
        int Eid = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value);
        string FirstName = ((TextBox)row.Cells[2].Controls[0]).Text.ToString().Trim();
        string LastName = ((TextBox)row.Cells[3].Controls[0]).Text.ToString().Trim();
        string Address = ((TextBox)row.Cells[4].Controls[0]).Text.ToString().Trim();
        string Mobile = ((TextBox)row.Cells[5].Controls[0]).Text.ToString().Trim();




  string sql = "UPDATE EMPLOYEE SET FIRSTNAME='" + FirstName +      "',LastName='" + LastName + "',Address='" +Address + "',Mobile='" + Mobile + "' WHERE EMPID=" + Eid + "";


        SqlCommand cmd = new SqlCommand(sql, con);
        con.Open();
        int temp = cmd.ExecuteNonQuery();
        con.Close();
        if (temp == 1)
        {
            
            lblMessage.Text = "Record updated successfully";
        }
        GridView1.EditIndex = -1;
        FillGrid();
    }


    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {        
        int Eid = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value);       
        SqlCommand cmd = new SqlCommand("DELETE FROM EMPLOYEE WHERE EMPID=" + Eid + "", con);
        con.Open();
        int temp = cmd.ExecuteNonQuery();
        if (temp == 1)
        {
            lblMessage.Text = "Record deleted successfully";
        }
        con.Close();
        FillGrid();


    }


    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridView1.EditIndex = e.NewPageIndex;
        FillGrid();
        
    }


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


Friday, December 24, 2010

how to insert value in identity column in sqlserver

 Syntax:-


        Set identity_insert table_name on
           ----insert query----
         Set identity_insert table_name off


Example


SET IDENTITY_INSERT EMPLOYEE ON


     INSERT INTO EMPLOYEE(ID,NAME,ADD)
        VALUES(1988,'Shivam Gupta','New Delhi')


SET IDENTITY_INSERT EMPLOYEE OFF


Note:- here "Employee" is table name and "id" is identity column in employee table.

Tuesday, December 21, 2010

Coding of LogOut Button in asp.net C#.

Coding of LogOut Button in asp.net C#.


you can use logout button in your master page.
Step1-: First be remove the cache in load event of master page. like describe below.




 protected void Page_Load(object sender, EventArgs e)
    {     
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
    }



Step2:- Now write the below code in click event of link button.


       protected void lnk_Click(object sender, EventArgs e)
    {
        Session.Abandon();
        
        Response.Redirect("~/Home.aspx");
    }

Coding of master page. 

public partial class InMaster : System.Web.UI.MasterPage
{
    protected void Page_Load(object sender, EventArgs e)
    {     
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
    }
    protected void lnk_Click(object sender, EventArgs e)
    {
        Session.Abandon();
        
        Response.Redirect("~/Home.aspx");
    }
}

How many language supported by asp.net

How many language supported by asp.net?
 Total 44 language is supported by asp.net
eg. C#,Vb,cobol, javascript, perl. etc..

Difference between Asp and Asp.net

How Asp.net different from Asp?

  * Scripting is separated from html in asp.net .
  * Code is compiled as a dll, these dll's can be executed on server.

Difference between boxing and unboxing

Difference between boxing and unboxing in asp.net C#
              Boxing allows us to convert value type to reference type. Basically , the run time create a temporary reference-type box for the object on heap.
Example:-
                int i = 20;
                object ob=i;     //Boxing.

ViewState with example in asp.net C#

  • ViewState:- The web is stateless but in asp.net, the state of page is maintained in the page itself automatically. How? The values are encryped and saved in hidden controls this is done automatically by the asp.net. This can be switched off/on manually for a single control.
Advantages :- Have a manually manage refreshing the page fields after submit.
Disadvantages:- Send additional data to the browser.
Example:-  We can store any thing in the viewstate manually and access it in same page.
      In this example we are saving the data table in view state and access it later in page.
Step1:- We  get the data table from database in page load event and store it in view state.

protected void Page_Load(object sender, EventArgs e)
    {
       string str = System.Configuration.ConfigurationManager.AppSettings["keyString"];
        SqlConnection con = new SqlConnection(str);
        SqlDataAdapter adap = new SqlDataAdapter("select * from product", con);
       DataTable dt = new DataTable();
       adap.Fill(dt);
       ViewState["TempTable"] = dt;
    }

Step2:-Now we access the table from viewstate on button click event and bind in gridview.

    protected void Button1_Click(object sender, EventArgs e)
    {
        GridView1.DataSource = (DataTable)ViewState["TempTable"];
        GridView1.DataBind();
    }

Complete Solution:-
Your Aspx page:

<%@ 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>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
    </div>
    <asp:GridView ID="GridView1" runat="server">
    </asp:GridView>
    <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
    
    </form>
</body>
</html>

Now your aspx.cs page

using System.Web.UI;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string str = System.Configuration.ConfigurationManager.AppSettings["keyString"];
        SqlConnection con = new SqlConnection(str);
        SqlDataAdapter adap = new SqlDataAdapter("select * from product", con);
       DataTable dt = new DataTable();
       adap.Fill(dt);
       ViewState["TempTable"] = dt;
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        GridView1.DataSource = (DataTable)ViewState["TempTable"];
        GridView1.DataBind();
    }
}

I hope it will help you.


Saturday, December 18, 2010

Tuesday, December 14, 2010

How to Move Image or Text in asp.net web Application

You can move the images or text in any direction in your web application files of asp.net

Step1- Move Image in up direction.
<marquee direction="up" style="height:30px; width: 319px"><asp:Image ID="img1" runat="server"
        ImageUrl="~/Image/moon.jpg" Width="472px" Height="416px" /></marquee>

Step 2 Move Text in right direction

<marquee direction="right" style="height:30px; width: 319px">
<aps:Label  ID="lblText" runat="server" Text="Hallow dear"/>
</marquee>

Finally you can write any thing inside the marquee tag that will move in appropriate direction as you want.

How to make secure web application

Step1->The best way to add logout button in your master page instead of each page in your application
  
Demonstration:- <asp:LinkButton ID="lnk" runat="server" Text="Logout" ForeColor="white"
                onclick="lnk_Click" CausesValidation="false"></asp:LinkButton>

Step2-> Now remove the session from cache, To do it, write the following code in page_load event of your master page in which you have logout button.

Demonstration:-

                           protected void Page_Load(object sender, EventArgs e)
                            {
                                     Response.Cache.SetCacheability(HttpCacheability.NoCache);
                             }

Step3-> Now write the following code in click event of link button

Demonstration:-
                         protected void lnk_Click(object sender, EventArgs e)
                                   {
                                       Session.Abandon();      
                                        Response.Redirect("~/Home.aspx");
                                   }

After performing all these steps your logout button will perform fine,
If you want to make more secure of your web application then you need to add Global.asax file in your web application. We define an event in this file that will perform globally and provide security from intruders.

Step1-> *Right click on your web application .
             *Add new item.
             *Add Global.asax file.

Step2-> Write a function in your Global.asax file as mention below.

                       void session_start()
                            {
                              if (Session["usr"] == null)
                                {
                                     Response.Redirect("~/Home.aspx");
                                    //Here you can write the address of your home page or index page
                                    // Or which you want to make start page.
                                 }
                          }


Now your web application is secure. If any one  paste the url of  any  page of your web application in the browser but browser will show only home or index page of your web application insteade of appropriate page. This is because your Global.asax file that works globally.
<a herf=" http://aspnet-with-c-sharp.blogspot.com/"> Logout button in your web application</a>
    

Wednesday, December 1, 2010

asp.net with C#: All Time Editable GridView in asp.net with C#

asp.net with C#: All Time Editable GridView in asp.net with C#: "This post demonstrate how to make a GridView editable all the time using C# asp.net. step1-: Create a table with name ' items' with follow..."

All Time Editable GridView in asp.net with C#

This post demonstrate  how to make a GridView editable all the time using C# asp.net.

step1-: Create a table with name " items" with following columns("iterm_no","name","price")
            where "iterm_no" is identity column.as describe below

            create table items
            (
               iterm_no int identity(1,1),
              name varchar(20),
              price numeric(10,2)
           )

step2- Now create a web page with name(EditableGridView). as describe below.

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

<!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>Editable GridView</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
  
    <asp:GridView ID="GridView1" runat="server" AllowPaging="True" AutoGenerateColumns="False"
BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px"
CellPadding="3" DataKeyNames="INTERM_NO" >
<FooterStyle BackColor="White" ForeColor="#000066" />
<Columns>
<asp:BoundField DataField="INTERM_NO" HeaderText="ITEM_N0" InsertVisible="False" ReadOnly="True"
SortExpression="INTERM_NO" />
<asp:TemplateField HeaderText="NAME" SortExpression="NAME">
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("NAME") %>'
OnTextChanged="TextBox_TextChanged" BorderStyle="None"></asp:TextBox>
<asp:HiddenField ID="HiddenField1" runat="server" Value='<%# Eval("INTERM_NO") %>' />
</ItemTemplate>
</asp:TemplateField>


<asp:TemplateField HeaderText="PRICE" SortExpression="PRICE">
<ItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("PRICE") %>'
OnTextChanged="TextBox_TextChanged" BorderStyle="None"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>



</Columns>
<RowStyle ForeColor="#000066" />
<SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left" />
<HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" />
</asp:GridView>
    </div>
    <asp:Button ID="btnUpdate" runat="server" onclick="btnUpdate_Click"
        Text="Update" />
    <asp:Label ID="lblMessage" runat="server"></asp:Label>
    </form>
</body>
</html>

step 3- Go to your code behind (EditableGridView.cs) as describe below.

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

public partial class EditableGridView : System.Web.UI.Page
{
  
    SqlConnection con;
    bool[] rowChanged;
    protected void Page_Load(object sender, EventArgs e)
    {
        string conString = ConfigurationSettings.AppSettings["mycon"];
        con = new SqlConnection(conString);
        int totalRows = GridView1.Rows.Count;
        rowChanged = new bool[totalRows];
        if (!Page.IsPostBack)
        {
            BindGrid();
        }
    }

    public void BindGrid()
    {
        SqlDataAdapter adap = new SqlDataAdapter("select * from items", con);
        DataTable dt = new DataTable();
        adap.Fill(dt);
        GridView1.DataSource = dt;
        GridView1.DataBind();
    }

    protected void TextBox_TextChanged(object sender, EventArgs e)
    {
        TextBox thisTextBox = (TextBox)sender;
        GridViewRow thisGridViewRow = (GridViewRow)thisTextBox.Parent.Parent;
        int row = thisGridViewRow.RowIndex;
        rowChanged[row] = true;
    }
 


    protected void btnUpdate_Click(object sender, EventArgs e)
    {
        if (Page.IsPostBack)
        {
            int totalRows = GridView1.Rows.Count;
            for (int r = 0; r < totalRows; r++)
            {
                if (rowChanged[r])
                {
                    GridViewRow thisGridViewRow = GridView1.Rows[r];
                    HiddenField hf1 = (HiddenField)thisGridViewRow.FindControl("HiddenField1");
                    string pk = hf1.Value;
                    TextBox tb1 = (TextBox)thisGridViewRow.FindControl("TextBox1");
                    string name = tb1.Text;
                    TextBox tb2 = (TextBox)thisGridViewRow.FindControl("TextBox2");
                    decimal price = Convert.ToDecimal(tb2.Text);

                    SqlCommand cmd = new SqlCommand("update items set name='" + name + "' , price='" + price + "' where INTERM_NO=' " + pk + "'", con);
                    if (con.State == ConnectionState.Closed)
                    {
                        con.Open();
                    }
                    int temp = cmd.ExecuteNonQuery();
                    if (temp > 0)
                    {
                        lblMessage.Text = "Operation perform successfully";
                        con.Close();
                    }


                }
            }
            GridView1.DataBind();
            BindGrid();
        }
    }
}

Note: If you have any query or question about this post contact us: