Thursday, 5 September 2013

Insert , update and Delete in Gridview with Entity

Insert , update and Delete in Gridview








Aspx page Code  

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

<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server" style="text-align :center ;">
    <div style="text-align:center; width :600px; margin-left:auto;margin-right:auto; font-weight: 700;">


    <table style="width:200px; margin-left:auto; margin-right :auto; ">
    <tr>
    <td>Name</td>
    <td>
            <asp:TextBox ID="txtname" runat="server" >
            </asp:TextBox></td>
   
    </tr>
    <tr>
    <td>Address</td>
    <td>
            <asp:TextBox ID="txtaddress" runat="server">
            </asp:TextBox></td>
   
    </tr>
       
    <tr>
    <td></td>
    <td><asp:Button ID="Button1" runat="server" Text="Add" onclick="Button1_Click" /></td>
    </tr>
   
    </table>
    <br />
        <asp:GridView ID="gvstudent" runat="server" AutoGenerateColumns="false"
            EmptyDataText="Record not Found"
            onrowcancelingedit="gvstudent_RowCancelingEdit"
            onrowediting="gvstudent_RowEditing" onrowdeleting="gvstudent_RowDeleting" onrowupdating="gvstudent_RowUpdating"
             >
            <Columns>
                <asp:TemplateField HeaderText ="Id">
                    <ItemTemplate>
                        <asp:Label ID="lblid" runat="server" Text='<%# Eval("id") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText ="Name">
                <ItemStyle Width="180px" />
                    <ItemTemplate>
                        <asp:Label ID="lblname" runat="server" Text='<%# Eval("name") %>'></asp:Label>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:TextBox ID="txtname" runat="server" Text='<%# bind("name") %>'></asp:TextBox>
                    </EditItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Address">
                <ItemStyle Width="180px" />
                    <ItemTemplate>
                        <asp:Label ID="lbladdress" runat="server" Text='<%# Eval("stu_add") %>'></asp:Label>
                    </ItemTemplate>
                   
                    <EditItemTemplate>
                        <asp:TextBox ID="txtaddress" runat="server" Text='<%# bind("stu_add") %>'></asp:TextBox>
                    </EditItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField>
                <ItemTemplate>
                <asp:Button ID="btnDelete" runat="server" Commandname="Delete"  CommandArgument ='<%# Container.DataItemIndex %>' Text="Delete" />
                 <asp:Button ID="btnEdit" runat="server" CommandName="Edit" CommandArgument ='<%# Container.DataItemIndex %>' Text="Edit" />
               
                </ItemTemplate>
                <EditItemTemplate>
                <asp:Button ID="btnupdate" runat="server" CommandArgument='<%# Container.DataItemIndex %>' CommandName="Update" Text="Update" />
                <asp:Button ID="btncanel" runat="server" CommandArgument='<%# Container.DataItemIndex %>' CommandName ="Cancel" Text ="Cancel" />
               
                </EditItemTemplate>
               
               
               
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
    </div>
    </form>
</body>
</html>

Aspx.cs Code

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

public partial class _Default : System.Web.UI.Page
{
    /// <summary>
    /// Create a object publicaly
    /// </summary>
    restaurentEntities entity = new restaurentEntities();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            gvbind();
        }
    }
    /// <summary>
    /// Method for bind GridView
    /// </summary>
    protected void gvbind()
    {
        gvstudent.DataSource = entity.stu_info.Select(x => x).ToList();
        gvstudent.DataBind();
    }
    /// <summary>
    /// Method for creating row into edit mode
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void gvstudent_RowEditing(object sender, GridViewEditEventArgs e)
    {
        gvstudent.EditIndex = e.NewEditIndex;
        gvbind();
    }

after click on Edit button in GridView will be look like as givent below:-





    /// <summary>
    /// Method for cancel Edit
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void gvstudent_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        gvstudent.EditIndex = -1;
        gvbind();
    }
    /// <summary>
    /// Method for Deletion row on behalf of Id(primary key)
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void gvstudent_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        int id = Convert.ToInt32(((Label)gvstudent.Rows[e.RowIndex].Cells[0].Controls[1]).Text);

        var v = entity.stu_info.Where(x => x.id == id).Select(x => x).FirstOrDefault();
        if (v != null)
        {
            entity.stu_info.DeleteObject(v);
            entity.SaveChanges();
        }
        gvbind();


    }
    /// <summary>
    /// Method for Add new Record and binding GridView
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Button1_Click(object sender, EventArgs e)
    {
        stu_info st = new stu_info();

        st.name = txtname.Text;
        st.stu_add = txtaddress.Text;
        entity.AddTostu_info(st);
        entity.SaveChanges();
        gvbind();
    }

    /// <summary>
    /// Method for updating a particular row on behalf of id( Primary Key)
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void gvstudent_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        int id = Convert.ToInt32(((Label)gvstudent.Rows[e.RowIndex].Cells[0].Controls[1]).Text);
        TextBox textname = (TextBox)gvstudent.Rows[e.RowIndex].Cells[1].FindControl("txtname");
        TextBox textaddress = (TextBox)gvstudent.Rows[e.RowIndex].Cells[2].FindControl("txtaddress");

        var v = entity.stu_info.Where(x => x.id == id).Select(x => x).FirstOrDefault();
        if (v != null)
        {
            v.name = textname.Text;
            v.stu_add = textaddress.Text;

            entity.SaveChanges();
        }
        gvstudent.EditIndex = -1;
        gvbind();
    }
}

Monday, 2 September 2013

Data Access Layer in C#

How To Create Three Tier Architecture in C# .net


First we add Class Library Project

Now add an Interface

Code for IDBManager.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Odbc;
using System.Data.SqlClient;
using System.Data.OleDb;
using System.Data.OracleClient;
using System.Data;

namespace dataaccesslayer
{
    public enum DataProvider
    {
        Oracle, SqlServer, OleDb, Odbc
    }
    public interface IDBManager
    {
        DataProvider ProviderType
        {
            get;
            set;
        }
        string ConnectionString
        {
            get;
            set;
        }
        IDbConnection Connection
        {
            get;
        }
        IDbTransaction Transaction
        {
            get;
        }
        IDataReader DataReader
        {
            get;
        }
        IDbCommand Command
        {
            get;
        }
        IDbDataParameter[] Parameters
        {
            get;
        }
        void Open();
        void BeginTransaction();
        void CommitTransaction();
        void CreateParameters(int paramsCount);
        void AddParameters(int index, string paramName, object objValue);
        IDataReader ExecuteReader(CommandType commandType, string commandText);
        DataSet ExecuteDataSet(CommandType commandType, string commandText);
        object ExecuteScalar(CommandType commandType, string commandText);
        int ExecuteNonQuery(CommandType commandType, string commandText);
        void CloseReader();
        void Close();
        void Dispose();
    }

}


Now add a Class DBManager.cs



Code for DBManager.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.OleDb;
using System.Data.Odbc;
using System.Data.OracleClient;

namespace dataaccesslayer
{



    public sealed class DBManagerFactory
    {
        private DBManagerFactory() { }
        public static IDbConnection GetConnection(DataProvider providerType)
        {
            IDbConnection iDbConnection = null;
            switch (providerType)
            {
                case DataProvider.SqlServer:
                    iDbConnection = new SqlConnection();
                    break;
                case DataProvider.OleDb:
                    iDbConnection = new OleDbConnection();
                    break;
                case DataProvider.Odbc:
                    iDbConnection = new OdbcConnection();
                    break;
                case DataProvider.Oracle:
                    iDbConnection = new OracleConnection();
                    break;
                default:
                    return null;
            }
            return iDbConnection;
        }

        public static IDbCommand GetCommand(DataProvider providerType)
        {
            switch (providerType)
            {
                case DataProvider.SqlServer:
                    return new SqlCommand();
                case DataProvider.OleDb:
                    return new OleDbCommand();
                case DataProvider.Odbc:
                    return new OdbcCommand();
                case DataProvider.Oracle:
                    return new OracleCommand();
                default:
                    return null;
            }
        }

        public static IDbDataAdapter GetDataAdapter(DataProvider providerType)
        {
            switch (providerType)
            {
                case DataProvider.SqlServer:
                    return new SqlDataAdapter();
                case DataProvider.OleDb:
                    return new OleDbDataAdapter();
                case DataProvider.Odbc:
                    return new OdbcDataAdapter();
                case DataProvider.Oracle:
                    return new OracleDataAdapter();
                default:
                    return null;
            }
        }

        public static IDbTransaction GetTransaction(DataProvider providerType)
        {
            IDbConnection iDbConnection = GetConnection(providerType);
            IDbTransaction iDbTransaction = iDbConnection.BeginTransaction();
            return iDbTransaction;
        }

        public static IDataParameter GetParameter(DataProvider providerType)
        {
            IDataParameter iDataParameter = null;
            switch (providerType)
            {
                case DataProvider.SqlServer:
                    iDataParameter = new SqlParameter();
                    break;
                case DataProvider.OleDb:
                    iDataParameter = new OleDbParameter();
                    break;
                case DataProvider.Odbc:
                    iDataParameter = new OdbcParameter();
                    break;
                case DataProvider.Oracle:
                    iDataParameter = new OracleParameter();
                    break;

            }
            return iDataParameter;
        }

        public static IDbDataParameter[] GetParameters(DataProvider providerType, int paramsCount)
        {
            IDbDataParameter[] idbParams = new IDbDataParameter[paramsCount];

            switch (providerType)
            {
                case DataProvider.SqlServer:
                    for (int i = 0; i < paramsCount; ++i)
                    {
                        idbParams[i] = new SqlParameter();
                    }
                    break;
                case DataProvider.OleDb:
                    for (int i = 0; i < paramsCount; ++i)
                    {
                        idbParams[i] = new OleDbParameter();
                    }
                    break;
                case DataProvider.Odbc:
                    for (int i = 0; i < paramsCount; ++i)
                    {
                        idbParams[i] = new OdbcParameter();
                    }
                    break;
                case DataProvider.Oracle:
                    for (int i = 0; i < paramsCount; ++i)
                    {
                        idbParams[i] = new OracleParameter();
                    }
                    break;
                default:
                    idbParams = null;
                    break;
            }
            return idbParams;
        }
    }
    public sealed class DBManager : IDBManager, IDisposable
    {
        private IDbConnection idbConnection;
        private IDataReader idataReader;
        private IDbCommand idbCommand;
        private DataProvider providerType;
        private IDbTransaction idbTransaction = null;
        private IDbDataParameter[] idbParameters = null;
        private string strConnection;

        public DBManager()
        {

        }

        public DBManager(DataProvider providerType)
        {
            this.providerType = providerType;
        }

        public DBManager(DataProvider providerType, string connectionString)
        {
            this.providerType = providerType;
            this.strConnection = connectionString;
        }

        public IDbConnection Connection
        {
            get
            {
                return idbConnection;
            }
        }

        public IDataReader DataReader
        {
            get
            {
                return idataReader;
            }
            set
            {
                idataReader = value;
            }
        }

        public DataProvider ProviderType
        {
            get
            {
                return providerType;
            }
            set
            {
                providerType = value;
            }
        }

        public string ConnectionString
        {
            get
            {
                return strConnection;
            }
            set
            {
                strConnection = value;
            }
        }

        public IDbCommand Command
        {
            get
            {
                return idbCommand;
            }
        }

        public IDbTransaction Transaction
        {
            get
            {
                return idbTransaction;
            }
        }

        public IDbDataParameter[] Parameters
        {
            get
            {
                return idbParameters;
            }
        }

        public void Open()
        {
            idbConnection = DBManagerFactory.GetConnection(this.providerType);
            idbConnection.ConnectionString = this.ConnectionString;
            if (idbConnection.State != ConnectionState.Open)
                idbConnection.Open();
            this.idbCommand = DBManagerFactory.GetCommand(this.ProviderType);
        }

        public void Close()
        {
            if (idbConnection.State != ConnectionState.Closed)
                idbConnection.Close();
        }

        public void Dispose()
        {
            GC.SuppressFinalize(this);
            this.Close();
            this.idbCommand = null;
            this.idbTransaction = null;
            this.idbConnection = null;
        }

        public void CreateParameters(int paramsCount)
        {
            idbParameters = new IDbDataParameter[paramsCount];
            idbParameters = DBManagerFactory.GetParameters(this.ProviderType,
              paramsCount);
        }

        public void AddParameters(int index, string paramName, object objValue)
        {
            if (index < idbParameters.Length)
            {
                idbParameters[index].ParameterName = paramName;
                idbParameters[index].Value = objValue;
            }
        }

        public void BeginTransaction()
        {
            if (this.idbTransaction == null)
                idbTransaction =
                DBManagerFactory.GetTransaction(this.ProviderType);
            this.idbCommand.Transaction = idbTransaction;
        }

        public void CommitTransaction()
        {
            if (this.idbTransaction != null)
                this.idbTransaction.Commit();
            idbTransaction = null;
        }

        public IDataReader ExecuteReader(CommandType commandType, string commandText)
        {
            this.idbCommand = DBManagerFactory.GetCommand(this.ProviderType);
            idbCommand.Connection = this.Connection;
            PrepareCommand(idbCommand, this.Connection, this.Transaction,
             commandType,
              commandText, this.Parameters);
            this.DataReader = idbCommand.ExecuteReader();
            idbCommand.Parameters.Clear();
            return this.DataReader;
        }

        public void CloseReader()
        {
            if (this.DataReader != null)
                this.DataReader.Close();
        }

        private void AttachParameters(IDbCommand command, IDbDataParameter[] commandParameters)
        {
            foreach (IDbDataParameter idbParameter in commandParameters)
            {
                if ((idbParameter.Direction == ParameterDirection.InputOutput)
                &&
                  (idbParameter.Value == null))
                {
                    idbParameter.Value = DBNull.Value;
                }
                command.Parameters.Add(idbParameter);
            }
        }

        private void PrepareCommand(IDbCommand command, IDbConnection connection, IDbTransaction transaction, CommandType commandType, string commandText, IDbDataParameter[] commandParameters)
        {
            command.Connection = connection;
            command.CommandText = commandText;
            command.CommandType = commandType;

            if (transaction != null)
            {
                command.Transaction = transaction;
            }

            if (commandParameters != null)
            {
                AttachParameters(command, commandParameters);
            }
        }

        public int ExecuteNonQuery(CommandType commandType, string commandText)
        {
            this.idbCommand = DBManagerFactory.GetCommand(this.ProviderType);
            PrepareCommand(idbCommand, this.Connection, this.Transaction,
            commandType, commandText, this.Parameters);
            int returnValue = idbCommand.ExecuteNonQuery();
            idbCommand.Parameters.Clear();
            return returnValue;
        }

        public object ExecuteScalar(CommandType commandType, string commandText)
        {
            this.idbCommand = DBManagerFactory.GetCommand(this.ProviderType);
            PrepareCommand(idbCommand, this.Connection, this.Transaction,
            commandType,
              commandText, this.Parameters);
            object returnValue = idbCommand.ExecuteScalar();
            idbCommand.Parameters.Clear();
            return returnValue;
        }
      
        public DataSet ExecuteDataSet(CommandType commandType, string commandText)
        {
            this.idbCommand = DBManagerFactory.GetCommand(this.ProviderType);
            PrepareCommand(idbCommand, this.Connection, this.Transaction,commandType,commandText, this.Parameters);
            IDbDataAdapter dataAdapter = DBManagerFactory.GetDataAdapter
              (this.ProviderType);
            dataAdapter.SelectCommand = idbCommand;
            DataSet dataSet = new DataSet();
            dataAdapter.Fill(dataSet);
            idbCommand.Parameters.Clear();
            return dataSet;
        }
    }

}                                        


Now Add a Static Class
Code for Static Class Connection

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Web;



namespace dataaccesslayer
{
  public static    class connection
    {


 
      public static  string connectionstring()

      {
        
     
      return ConfigurationManager.ConnectionStrings["restaurant"].ConnectionString;
     
      }
    }
}