Friday, May 11, 2012

Insert Multiple Records into Database from GridView


     This is a common concept,  which we use in our project maximum times. User stores records into gridview one after another and save all records from gridview into database at a single push.

Before starting the project we have to design the table according to our requirement

Table  Design


Column                  DataType
StudentRoll(PK)   varchar(20)
StudentAge int
StudentAddress varchar(50)


Source Code (Design View)


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Multiple datainsert in database by gridview.aspx.cs" Inherits="Multiple_datainsert_in_database_by_gridview" %>

<!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>
    <style type="text/css">
        .style1
        {
            width: 100%;
        }
    </style>
</head>
<body>
    <form id="form2" runat="server">
    <div>
 
        <table class="style1">
            <tr>
                <td>
                    &nbsp;</td>
                <td>
                    &nbsp;</td>
            </tr>
            <tr>
                <td>
                    &nbsp;</td>
                <td>
                    &nbsp;</td>
            </tr>
            <tr>
                <td style="text-align: right">
    <asp:Label ID="Label1" runat="server" Text="Roll"></asp:Label>
                </td>
                <td>
     
        <asp:TextBox ID="TextBox1" runat="server" ></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td width="40%" style="text-align: right">
    <asp:Label ID="Label2" runat="server" Text="Name" ></asp:Label>
                </td>
                <td width="60%">

 
        <asp:TextBox ID="TextBox2" runat="server" ></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td style="text-align: right">
    <asp:Label ID="Label3" runat="server" Text="Address"></asp:Label>
 
                </td>
                <td>
        <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    &nbsp;</td>
                <td>
                  <asp:Button ID="Button1" runat="server" Text="Add" onclick="Button1_Click"/>
    <asp:Button ID="Button2" runat="server" Text="Save" onclick="Button2_Click" />
    <asp:Button ID="Button3" runat="server" Text="Clear" onclick="Button3_Click" />

                    &nbsp;</td>
            </tr>
        </table>

        &nbsp;

    <asp:GridView ID="GridView1" runat="server" >
    </asp:GridView>
    </div>
 
    </form>
</body>
</html>

 C# Code

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;

public partial class Multiple_datainsert_in_database_by_gridview : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection("Data source=.\\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\\Database.mdf;User Instance=true");
    SqlCommand cmd;
    static int flag = 0;
    static int rowno = 0;
    DataTable dt;

    # region Method
    protected void fillGrid()
    {
        dt = new DataTable();
        dt = (DataTable)ViewState["Datatable"];
        if (dt.Rows.Count > 0)
        {
            GridView1.DataSource = dt;
            GridView1.DataBind();
        }
        else
        {
            GridView1.Dispose();
            GridView1.DataBind();
        }

    }
    public DataTable Createtable()
    {
        dt = new DataTable();
        dt.Columns.Add("Roll", typeof(int));
        dt.Columns.Add("Name", typeof(string));
        dt.Columns.Add("Address", typeof(string));
        ViewState["Datatable"] = dt;
        return dt;
    }
    # endregion

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Createtable();
        }
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        dt = new DataTable();
        dt = (DataTable)ViewState["Datatable"];
        DataRow dr;        
        dr = dt.NewRow();
        dr[0] = TextBox1.Text;
        dr[1] = TextBox2.Text;
        dr[2] = TextBox3.Text;
        dt.Rows.Add(dr);    
      
        ViewState["Datatable"] = dt;
        fillGrid();
    }
   
    protected void Button2_Click(object sender, EventArgs e)
    {
        foreach (GridViewRow r in GridView1.Rows)
        {
            int a = int.Parse(r.Cells[0].Text.Trim());
            string b = r.Cells[1].Text.Trim();
            string c = r.Cells[2].Text.Trim();
            SqlCommand cmd = new SqlCommand("Insert into Student values('" + a + "','" + b + "','" + c + "')", con);
            con.Open();
            cmd.ExecuteNonQuery();
            con.Close();
        }
    }

    protected void Button3_Click(object sender, EventArgs e)
    {
        ViewState["Datatable"] = null;       
        GridView1.DataSource = null;
        GridView1.DataBind();     
        Createtable();
    }
}

Wednesday, May 2, 2012

Working with Global.asax in ASP.net

  It is a Active Server Application file which contains the Application and Session events to keeping the information globally. It is a part of State Management in asp.net that provide to storing data at server side.A website can have only one Global.asax file.

   Step-1

    1. Add new Global.asax file if not added before
    2. Follow the Code below

 <%@ Application Language="C#" %>

<script runat="server">

    void Application_Start(object sender, EventArgs e)
    {
        // Code that runs on application startup
        Application["NoOfUser"] = 0;
        Application["OnLineUser"] = 0;

    }
   
    void Application_End(object sender, EventArgs e)
    {
        //  Code that runs on application shutdown

    }
       
    void Application_Error(object sender, EventArgs e)
    {
        // Code that runs when an unhandled error occurs

    }

    void Session_Start(object sender, EventArgs e)
    {
        // Code that runs when a new session is started
        Application.Lock();
        Application["NoOfUser"] = Convert.ToInt32(Application["NoOfUser"])+1;
        Application["OnLineUser"] = Convert.ToInt32(Application["OnLineUser"]) + 1;
        Application.UnLock();

    }

    void Session_End(object sender, EventArgs e)
    {
        // Code that runs when a session ends.
        // Note: The Session_End event is raised only when the sessionstate mode
        // is set to InProc in the Web.config file. If session mode is set to StateServer
        // or SQLServer, the event is not raised.
        Application.Lock();
        Application["OnLineUser"] = Convert.ToInt32(Application["OnLineUser"]) - 1;
        Application.UnLock();
    }
     
</script>


 Step-2
  
     1. Add new web form file if not added before
     2. Follow the Code below (I have taken it under a master page )
 
   Design page (Source code)

    <%@ Page Title="" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="FrmGlobal.aspx.cs" Inherits="StateManagement_FrmGlobal" %>

<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" Runat="Server">
    <div align="center">
   <fieldset style="width:300px;height:200px">
   
       <table class="style1">
         
         
           <tr>
               <td>
                   &nbsp;</td>
               <td>
                  <asp:Label ID="Label2" runat="server" Text=""></asp:Label>
                  <br />
                  <asp:Label ID="Label1" runat="server" Text=""></asp:Label>
               </td>
           </tr>
         
       </table>
   
 </fieldset>
</div>
</asp:Content>


C# code



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

public partial class StateManagement_FrmGlobal : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Session.Timeout = 1;
        Label2.Text ="Total Number of users are :"+ Application["NoOfUser"].ToString();
        Label1.Text ="On Line users are :" + Application["OnLineUser"].ToString();
    }
}

Every call of the application we can see the result

 

     

Tuesday, May 1, 2012

Working with Cookies in ASP.net


   Cookies are the part of a state management in asp.net to store server information at client side. It has two types
      a. In-Memory Cookies
b. Persistent Cookies

 In-Memory Cookies
     cookies information stored as long as the current application is opened.
  Persistent Cookies
    cookies information stored as long as the current application is opened and leave the the application (both online and offline).It is stored temporarily based on date and time.

         Page Design (Source code) :-
     
             <%@ Page Title="" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="FrmInMemoryCookies1.aspx.cs" Inherits="StateManagement_FrmInMemoryCookies1" %>

<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" Runat="Server">
    <style type="text/css">
        .style1
        {
            width: 100%;
        }
    </style>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" Runat="Server">
    <div align="center">
   <fieldset style="width:300px;height:200px">
 
       <table class="style1">
           <tr>
               <td>
                   &nbsp;</td>
               <td>
                   &nbsp;</td>
           </tr>
           <tr>
               <td>
                   &nbsp;</td>
               <td>
                   &nbsp;</td>
           </tr>
           <tr>
               <td style="text-align: right" width="30%">
                   <asp:Label ID="Label1" runat="server" Text="Enter Name"></asp:Label>
               </td>
               <td style="text-align: left" width="70%">
                   <asp:TextBox ID="TxtName" runat="server"></asp:TextBox>
               </td>
           </tr>
           <tr>
               <td>
                   &nbsp;</td>
               <td>
                   <asp:Button ID="BtnSubmit" runat="server" onclick="BtnSubmit_Click"
                       Text="In-MemoryCookies" />
                        <asp:Button ID="BtnPcookies" runat="server" Text="PersistentCookies"
                       onclick="BtnPcookies_Click" />
                   <asp:Button ID="BtnRefresh" runat="server" onclick="BtnRefresh_Click"
                       Text="ReStore" />
               </td>
           </tr>
           <tr>
               <td>
                   &nbsp;</td>
               <td>
                  <asp:Label ID="Label2" runat="server" Text=""></asp:Label>
               </td>
           </tr>
         
       </table>
 
 </fieldset>
</div>

</asp:Content>



C# Code :-



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

public partial class StateManagement_FrmInMemoryCookies1 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
     
            if (Request.Cookies["name"] == null)
            {
            }
            else
            {
                TxtName.Text = Request.Cookies["name"].Value;
            }
     
    }
    protected void BtnSubmit_Click(object sender, EventArgs e)
    {    

            HttpCookie x = new HttpCookie("name");
            x.Value = TxtName.Text;
            Response.Cookies.Add(x);
            Label2.Text = "Information Stored in Cookies";
            TxtName.Text = "";
     
    }
    protected void BtnRefresh_Click(object sender, EventArgs e)
    {
        Label2.Text = "Cookies Information ReStored";
    }
    protected void BtnPcookies_Click(object sender, EventArgs e)
    {
        HttpCookie x = new HttpCookie("name");
        x.Value = TxtName.Text;
        x.Expires = DateTime.Now.AddMinutes(5);
        Response.Cookies.Add(x);
        Label2.Text = "Information Stored in Cookies";
        TxtName.Text = "";
    }
}













Monday, April 30, 2012

Display Different Image in Gridview From Database on Condition

    Here I have created a table in which a column stores the image name of a product. Ex: I am saving a product details with its image name. And also created a Image folder in my application where I have stored the physical image file.I am only displaying the image in form load.

Table Design 


ProductID int
ProductName varchar(50)
ProductImage varchar(50)

Table With Data


1Samsungsamsung01.jpg
2LGlg01.jpg
NULLNULLNULL

Design  View( Source Code)



<%@ Page Title="" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="FrmGridViewStatus.aspx.cs" Inherits="FrmGridViewStatus" %>

<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" Runat="Server">
    <style type="text/css">
        .style1
        {
            width: 100%;
        }
    </style>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" Runat="Server">
    <table class="style1">
        <tr>
        <td>
                &nbsp;</td>
        </tr>
        <tr>
        <td>
                &nbsp;</td>
        </tr>
        <tr>
            <td>
                <asp:GridView ID="GridView1" runat="server" Width="370px"
                    AutoGenerateColumns="False">
                    <Columns>
                        <asp:BoundField DataField="id" HeaderText="ID" />
                        <asp:BoundField DataField="name" HeaderText="Name" />
                        <asp:TemplateField HeaderText="Photo">
                            <ItemTemplate>
                             
                                            <asp:Image ID="Image1" runat="server" ImageUrl='<%#GetImage(Eval("ProductImage").ToString())%>' Width="100" Height="100"/>           
                            </ItemTemplate>
                        </asp:TemplateField>
                    </Columns>
                </asp:GridView>
            </td>
        </tr>
        <tr>
            <td>
                &nbsp;</td>
        </tr>
        <tr>
            <td>
                &nbsp;</td>
        </tr>
    </table>
</asp:Content>

C# Code



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 FrmGridViewStatus : System.Web.UI.Page
{
    SqlConnection con;
    SqlCommand cmd;
    SqlDataReader dr;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (IsPostBack == false)
        {
            con = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString);
            getData();
        }

    }
    private void getData()
    {
        try
        {

            con.Open();
            cmd = new SqlCommand("select ProductID,ProductName,ProductImage from product",con);
            dr = cmd.ExecuteReader();
            GridView1.DataSource = dr;
            GridView1.DataBind();
            con.Close();

        }
        catch(Exception ex)
        {
        }
   
    }
    public string GetImage(string ProductImage )
    {
        string ImgURl = "";
        if (ProductImage != null)
        {
           ImgURl="~/Images/"+ProductImage ;
        }
        else{
         
        }
        return ImgURl;
    }
}






Fill Multiple GridView using DataReader Batch Select Statement

Design (Source Code)





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

<!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>
    <style type="text/css">
        .style1
        {
            width: 100%;
        }
        .style2
        {
            color: #FF0066;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
 
        <table class="style1">
            <tr>
                <td class="style2">
                    Fill Grid View using DataReader Multiple Select statement
                </td>
            </tr>
            <tr>
                <td>
                    <asp:GridView ID="GridViewLedger" runat="server">
                    </asp:GridView>
                </td>
            </tr>
            <tr>
                <td>
                    &nbsp;</td>
            </tr>
            <tr>
                <td>
                    <asp:GridView ID="GridViewDemo" runat="server">
                    </asp:GridView>
                </td>
            </tr>
              <tr>
                <td>
                    &nbsp;</td>
            </tr>
            <tr>
                <td>
                    <asp:GridView ID="GridViewParty" runat="server">
                    </asp:GridView>
                </td>
            </tr>
        </table>
 
    </div>
    </form>
</body>
</html>

C# code



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

public partial class FrmDataReader : System.Web.UI.Page
{
    SqlConnection con;
    SqlCommand cmd;
    SqlDataReader dr;

    protected void Page_Load(object sender, EventArgs e)
    {
     
        con = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString);    
        SelectData();    

    }
    private void SelectData()
    {
        try
        {
            con.Open();

         
            using (cmd = new SqlCommand("select top(10) ledgerid,ledgername  from fms.fms_ledgers;select * from fms_demo;select * from fms.fms_parties", con))
            {

                // in case of multiple result set you will not be able to specify the  CommandBehavior
                // if so you will not be able to get the next result set from the reader

                using (SqlDataReader reader = cmd.ExecuteReader())
                {
                    // bind the first resultset
                    GridViewLedger.DataSource = reader;
                    GridViewLedger.DataBind();

                    reader.NextResult();

                    // bind the second resultset
                    GridViewDemo.DataSource = reader;
                    GridViewDemo.DataBind();

                    reader.NextResult();

                    // bind the third resultset
                    GridViewParty.DataSource = reader;
                    GridViewParty.DataBind();

                }

            }

        }
        catch (Exception ex)
        {
            string x = ex.Message.ToString();
        }
        finally
        {
            con.Close();
        }
    }
}