MY bLOG

Wednesday, 5 March 2014

How to add validation controls to update event in gridview?

In this article  i will explain how to validate the controls which are placed in grid view
http://aswinialuri.blogspot.in/2014/03/how-to-insert-editdelete-update-and.html

In the above article i explained how to insert,edit,delete,update and cancelling operations in grid view using Asp.net.
So here  i will explain how to update the data using validation to avoid  empty cell upadating

code in .aspx page:

 <div>
    <asp:GridView ID="gridview" runat="server" AutoGenerateColumns="False" 
            AutoGenerateEditButton="True"  AutoGenerateDeleteButton="True" 
             DataKeyNames="Id" onrowcancelingedit="gridview_RowCancelingEdit" 
            onrowdeleting="gridview_RowDeleting" onrowediting="gridview_RowEditing" 
            onrowupdating="gridview_RowUpdating" >
            
            <Columns><asp:TemplateField HeaderText="Id"><ItemTemplate><asp:Label ID="lbl_id" runat="server" Text='<%#Eval("Id")%>'></asp:Label>
            </ItemTemplate>
            <EditItemTemplate><asp:TextBox ID="txt_id" runat="server" Text='<%#Eval("Id")%>'></asp:TextBox>
            </EditItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Name"><ItemTemplate><asp:Label ID="lbl_name" runat="server" Text='<%#Eval("Name")%>'></asp:Label>
            </ItemTemplate>
            <EditItemTemplate><asp:TextBox ID="txt_name" runat="server" Text='<%#Eval("Name")%>'></asp:TextBox>
            </EditItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Salary"><ItemTemplate><asp:Label ID="lbl_sal" runat="server" Text='<%#Eval("salary")%>'></asp:Label>
            </ItemTemplate>
            <EditItemTemplate><asp:TextBox ID="txt_salary" runat="server" Text='<%#Eval("salary")%>'></asp:TextBox>
            </EditItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Department"><ItemTemplate><asp:Label ID="lbl_dept" runat="server" Text='<%#Eval("Department")%>'></asp:Label>
            </ItemTemplate>
            <EditItemTemplate><asp:TextBox ID="txt_dept" runat="server" Text='<%#Eval("Department")%>'></asp:TextBox>
                <asp:RequiredFieldValidator ID="RequiredFieldValidator1" ControlToValidate="txt_dept" Text="*" runat="server" ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator>
            </EditItemTemplate>
            </asp:TemplateField>
             </Columns>
        </asp:GridView>
        <br />
    </div>
    <table><tr><td>Id:</td><td>
            <asp:TextBox ID="txt_id" runat="server"></asp:TextBox></td></tr>
            <tr><td>Name:</td><td>
                <asp:TextBox ID="txt_name" runat="server"></asp:TextBox></td></tr>
                <tr><td>Salary:</td><td>
                    <asp:TextBox ID="txt_salary" runat="server"></asp:TextBox></td></tr>
                    <tr><td>Department:</td><td>
                        <asp:TextBox ID="txt_dept" runat="server"></asp:TextBox></td></tr>
                        <tr><td colspan="2" align="center">
                            <asp:Button ID="btn_submit" runat="server" Text="Submit" 
                                onclick="btn_submit_Click" /></td></tr>

            </table>

code in .aspx.cs page:

//To update a row event
 protected void gridview_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        GridViewRow row = gridview.Rows[e.RowIndex] as GridViewRow;
        int id = Convert.ToInt32(gridview.DataKeys[e.RowIndex].Values["Id"].ToString());
        TextBox txtname = (TextBox)gridview.Rows[e.RowIndex].FindControl("txt_name");
        TextBox txtsalary = (TextBox)gridview.Rows[e.RowIndex].FindControl("txt_salary");
        TextBox txtdepartment = (TextBox)gridview.Rows[e.RowIndex].FindControl("txt_dept");
        SqlConnection con = new SqlConnection(strcon);
        SqlCommand cmd = new SqlCommand("update Emp1 set Name=@Name,salary=@salary,Department=@Department "+" where Id=@Id", con);
        cmd.Parameters.AddWithValue("@Name", txtname.Text);
        cmd.Parameters.AddWithValue("@salary", txtsalary.Text);
        cmd.Parameters.AddWithValue("@Department", txtdepartment.Text);
        cmd.Parameters.AddWithValue("@Id",id);
        con.Open();
        cmd.ExecuteNonQuery();
        gridview.EditIndex = -1;
        con.Close();
        binddata();

    }
I f you click on update button 
required field validator is set into the department if you leave the text box empty it shown an error so the row will not be updated and you will assign the text for particular department .

I hope you understand the article how to validate the text in row event
If you have any queries make a comment.

How to Insert, Edit,Delete ,Update and Canceling in Grid view using asp.net?

In this article i will explain how to insert edit update delete and canceling operations in grid view

You can achieve by using the
1.onrowediting-Is used to Edit the particular row
2.onrowupdating-Is used to update the particular row
3.onrowdeleting-Is used to delete the particular row
4.onrowcancelingedit-Is used to cancel the particular row

code in .aspx page:


<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
            AutoGenerateEditButton="True" onrowediting="GridView1_RowEditing" 
            onrowupdating="GridView1_RowUpdating" AutoGenerateDeleteButton="True" 
            onrowdeleting="GridView1_RowDeleting" DataKeyNames="Id" 
            onrowcancelingedit="GridView1_RowCancelingEdit">
            <Columns><asp:TemplateField HeaderText="Id"><ItemTemplate><asp:Label ID="lbl_id" runat="server" Text='<%#Eval("Id")%>'></asp:Label>
            </ItemTemplate>
            <EditItemTemplate><asp:TextBox ID="txt_id" runat="server" Text='<%#Eval("Id")%>'></asp:TextBox>
            </EditItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Name"><ItemTemplate><asp:Label ID="lbl_name" runat="server" Text='<%#Eval("Name")%>'></asp:Label>
            </ItemTemplate>
            <EditItemTemplate><asp:TextBox ID="txt_name" runat="server" Text='<%#Eval("Name")%>'></asp:TextBox>
            </EditItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Salary"><ItemTemplate><asp:Label ID="lbl_sal" runat="server" Text='<%#Eval("salary")%>'></asp:Label>
            </ItemTemplate>
            <EditItemTemplate><asp:TextBox ID="txt_salary" runat="server" Text='<%#Eval("salary")%>'></asp:TextBox>
            </EditItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Department"><ItemTemplate><asp:Label ID="lbl_dept" runat="server" Text='<%#Eval("Department")%>'></asp:Label>
            </ItemTemplate>
            <EditItemTemplate><asp:TextBox ID="txt_dept" runat="server" Text='<%#Eval("Department")%>'></asp:TextBox>
                </EditItemTemplate>
            </asp:TemplateField>
             </Columns>
        </asp:GridView>
        <br />
        <table><tr><td>Id:</td><td>
            <asp:TextBox ID="txt_id" runat="server"></asp:TextBox></td></tr>
            <tr><td>Name:</td><td>
                <asp:TextBox ID="txt_name" runat="server"></asp:TextBox></td></tr>
                <tr><td>Salary:</td><td>
                    <asp:TextBox ID="txt_salary" runat="server"></asp:TextBox></td></tr>
                    <tr><td>Department:</td><td>
                        <asp:TextBox ID="txt_dept" runat="server"></asp:TextBox></td></tr>
                        <tr><td colspan="2" align="center">
                            <asp:Button ID="btn_submit" runat="server" Text="Submit" 
                                onclick="btn_submit_Click" /></td></tr>
            </table>
    </div>

    </form>
create table in sql server
column name                       datatype

Id                                         Int(set identity property =true)
Name                                     Nvarchar(100)
Salary                                    Nvarchar(50)
Deprtment                             Nvarchar(50)

code in .aspx.cs page:
Add namespaces 
using System.Data;
using System.Data.SqlClient;
using System.Configuration;


 string strcon = ConfigurationManager.ConnectionStrings["sqlconn"].ConnectionString;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            getdata();
        }
    }
//To bind the data from database to grid view
    public void getdata()
    {
        SqlConnection con = new SqlConnection(strcon);
        SqlCommand cmd = new SqlCommand("select * from Emp", con);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        da.Fill(ds);
        GridView1.DataSource=ds;
        GridView1.DataBind();
    }
//To edit the the row event
    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        GridView1.EditIndex = e.NewEditIndex;
        getdata();
    }
//To update the row event
    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        GridViewRow row = GridView1.Rows[e.RowIndex] as GridViewRow;
        int Id = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values["Id"].ToString());
        TextBox tname = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txt_name");
        TextBox tsalary = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txt_salary");
        TextBox tdept = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txt_dept");
        SqlConnection con = new SqlConnection(strcon);
        SqlCommand cmd = new SqlCommand("update Emp set Name=@Name,salary=@salary,Department=@Department"+" where Id=@Id", con);
        cmd.Parameters.AddWithValue("@Name", tname.Text.Trim());
        cmd.Parameters.AddWithValue("@salary",tsalary.Text.Trim());
        cmd.Parameters.AddWithValue("@Department", tdept.Text.Trim());
        cmd.Parameters.AddWithValue("@Id", Id);
        con.Open();
        cmd.ExecuteNonQuery();
        GridView1.EditIndex = -1;
        getdata();
        con.Close();
   
    }
//To delete the row event
    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        int Id = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values["Id"].ToString());
        SqlConnection con = new SqlConnection(strcon);
        SqlCommand cmd = new SqlCommand("delete from Emp where Id=@Id", con);
        con.Open();
        cmd.Parameters.AddWithValue("@Id", Id);
        cmd.ExecuteNonQuery();
        
        GridView1.DataBind();
        con.Close();
        getdata();
    }
//To canceling the row
    protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        GridView1.EditIndex = -1;
        getdata();
    }
    protected void SqlDataSource1_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
    {
            }
//To insert the data and bind into gridview as well as data base
    protected void btn_submit_Click(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection(strcon);
        con.Open();
        SqlCommand cmd = new SqlCommand("emp_insert_sp", con);
        cmd.CommandType = CommandType.StoredProcedure;
        //cmd.Parameters.AddWithValue("@Id", txt_id.Text);
        cmd.Parameters.AddWithValue("@Name", txt_name.Text);
        cmd.Parameters.AddWithValue("@salary", txt_salary.Text);
        cmd.Parameters.AddWithValue("@Department", txt_dept.Text);
        cmd.ExecuteNonQuery();

        con.Close();
I hope you understand how to insert ,edit ,update ,delete and canceling in gridview using asp.net

OOPS Concepts

oops(Object oriented programming structure)

1.Abstraction 
2.Encapsulation
3.Polymorphism
4.Inheritance.

It can use while implementing the functionality of your projects ,according to your requirement
Class:
class is an user defined data type
class is a collection fields , Methods, properties and events.
A class exist logically whereas object exist physically
Public class Customer
{
}
Customer objCust=new Customer();

Object: Object is an instance of class
Syntax: customer ObjCust;
ObjCust=new customer();
Abstraction: Hiding the unnecessary details from the view of the users is called  abstraction
Or
 Hiding the implementation is known as Abstraction.
Abstraction is a process that involves identifying the critical behavior of an object and eliminating irrelevant and complex details.
Encapsulation:
Binding or Encapsulating the methods with the fields by providing the security for data.
Or
Accessing  the public properties by using private variables is one of the good example in encapsulation
Example:
private int _id;

    public int Id
    {
        get { return _id; }
        set { _id = value; }
    }
Here you are not accessing the private variable id but you are accessing the public property id
Polymorphism:
Same function with the different behavior   with different no of values is called is polymorphism
By achieving polymorphism in Three types:
Function Overloading, Operator overloading-early binding-compile time
Method Overloading:
Same function with different  signature is known as method overloading.
Function Overloading is implemented within the same  class.
Example:
public class class1
    {

        public int add(int a, int b)
        {
            return a + b;

        }

        public int add(int a, int b, int c)
        {
            return a + b + c;
        }
    }

Function overriding-late binding-run time Polymorphism
Method Overriding:
Overriding means changing the functionality of a method without changing the signature. We can override a function in base class by creating a similar function in derived class. This is done by usingvirtual/override keywords
class Baseclass
    {
       
            public virtual void A()
            {
                Console.WriteLine("BaseMethod");
            }

            public class derivedclass : Baseclass
            {
                public override void A()
                {
                    Console.WriteLine("DerivedMethod");
                }
           
        }
        static void Main(string[] args)
        {
            derivedclass objprog = new derivedclass();

            objprog.A();
            Baseclass objprog1 = new derivedclass();
            objprog1.A();
            Console.ReadLine();

        }
    }
o/P: Derived Method
     Derived Method

Method Hiding:
It is a concept of polymorphism while method shadowing redefines the whole element,
Shadowing helps you override a function in a parent method even if that is not marked virtual
 New keyword helps you to override a non-virtual method in the child class.
Example:
public class Baseclass
    {
public void A()
        {
            Console.WriteLine("BaseMethod");
        }

        public class derivedclass : Baseclass
        {
            public new void A()
            {
                Console.WriteLine("DerivedMethod");
            }
        }
        static void Main(string[] args)
        {
            derivedclass objprog = new derivedclass();
            objprog.A();
            Baseclass objprog1 = new derivedclass();
            objprog1.A();
            Console.ReadLine();
}
}
O/p: Derived Method
     Base Method.
The new keyword is used to hide the method because the base class method is not marked as
Virtual. If it is marked as virtual and if there is any overridable method is available then you will get derived method output.
Note:Overriding redefines only the element while shadowing redefines the whole element.

Inheritance: This is a process of creating a new class from already existing class
Whereas  existing class is known as parent class or Base class  and new class is known as child class or derived class, Inheritance is the purpose of code reusability and providing additional features.
Example:
public class Baseclass
    {
       public Baseclass()
       {
             Console.WriteLine ("Base Class");
    }
                                
    public void Write ()
    {
        Console.WriteLine ("Write method in baseclass");
    }
                               
public class ChildClass:Baseclass
{
                                
    public ChildClass ()
    {
        Console.WriteLine("Child Class");
    }
  
    public static void Main ()
    {
        ChildClass CC = new ChildClass ();
        CC.Write ();
        Console.ReadLine();
    }
}
       }
Types of Inheritance:
Single Inheritance: Creating Single new class from single base class is known as single inheritance.
Multiple Inheritance: Creating a new class from two or more base classes is known as multiple inheritance.
Note: In c# multiple inheritance is not possible  using inheritance instead of that you can use interfaces.
Mutli Level Inheritance: Creating a new class from already derived class is known as multilevel inheritance.

Hybrid Inheritance: It is the combination of multiple and Multilevel Inheritance

Monday, 3 February 2014

Backup and Restore using sql server?

This article will explain you how to restore the database and how to take an backup of our database file , different types of backup and how it will be used.

Introduction:

Backup is nothing but copy of original data.It is used when the your database is crashed by some problem the backup is used at the time.

They are seven types of Back Up's are there:
1)Full Backup
2)Differential Backup.
3)Transaction Log Backup.
4)Tail-Log(Point-in-time).
5)Mirror.
6)Copy-only.
7)File&File Group.

Full Backup:
Full Backup is used to take an entire database and extension is .bak 
Differential Backup:
Differential Backup is used to take the backup of the modify data or changed data after taking the full backup.
Extension .bak
Transaction Log Backup:
Transaction Log Backup is used to take the Current transaction backup 
Extension .trn
Tail-Log Backup:
Trail-Log Backup is used to take the backup of after crashing the database.
Extension .trn
Mirror Backup:
Mirror Backup is used to take the backup more than one disk.
Extension .bak
Copy-Only Backup:
Copy-only backup is used to take the backup with out disturbing the Mdf & ndf files.
Extension .bak
File &File Group Backup:
File&File Group Backup is used to take the individual Backup or group of files then we can use file or file group.
Extension .bak
Syntax for Full BackUp:
backup database<database name>to disk='Location\Full.bak' with stats=5
If it is in Differential log Backup then we indicate with differential stats

Syntax for Transaction log Backup
backup log database name from disk='location\tlog.trn with stats 2

Syntax for Tail-log Backup
same as transaction log slite change in point-in-time file name.

Syntax for Mirror Backup
backup database<database name> to disk='Location\Full.bak' mirror to disk='location\full.bak'.

Syntax for Copy-Only Backup:
backup database to disk='location with copy-only'.

File &File group:
File backup is nothing but take the backup of mdf files&ndf files.
To take the backup for individual files and file groups.


GUI Based Full Backup:

Open object Explorer in the toolbar,Now we can got to database folder and right click on tasks , Now select the backup 





Now click on backup and select backup type is Full change the location and click on Add button(change the previous location)

 Backup destination window should appear, select the location using browser button 

Now select the location and file name must be with the extension of .bak file which as shown below and click ok button.

Now select the options page select Overwrite all existing backup sets radio button and chech the checkbox verify 
backup when finished then click on ok.

After we click ok me get a message box then again click on ok

I hope this step by step process will help you to backup the database.


How to Restore the Database?
Syntax of Restore db:
Restore Database<database name>from Disk='Location\full.bak with No Recovery stats=10
GUI based:
 Open object explorer in the tool bar,Now we can go to database and right click on database and select restore database


Restore Window database should appear and type the database name on 'to database' and select device radio button and click browse button.

Select Backup device click add button with the extension of .bak


Select the checkbox 

Go to options page check the overwrite the existing database on restore option in Recovery state select Restore with Recovery and click on ok.

After we click ok we get message box which in our case says "Database database name restored successfully

This step by step tutorial will help you for restore the database.

By using this article we can easily restore and backup the database.
i hope you understand.

Thursday, 30 January 2014

How to insert the data into gridview using textboxes in asp.net?


I would like to explain about inserting values into textbox and that will be displayed in grid view 
so  for that  
In visual studio click on file -->New project-->Add weapplication-> add new item-->
add new web form

In .aspx page:

  <table>
        <tr><td>Name:</td><td>
            <asp:TextBox ID="txt_name" runat="server"></asp:TextBox></td></tr>
            <tr><td>Description:</td><td>
                <asp:TextBox ID="txt_description" runat="server"></asp:TextBox></td></tr>
                <tr><td>Department:</td><td>
                    <asp:TextBox ID="txt_depart" runat="server"></asp:TextBox></td></tr>
                    <tr><td colspan="2" align="center">
                        <asp:Button ID="Button1" runat="server" Text="Submit" onclick="Button1_Click" /></td></tr>
        </table>
<asp:label: id="1abel1" runat="server" >
The page will be display like this 
code in .aspx.cs page:
 using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.UI.WebControls;

namespace WebApplication1
{
    public partial class insert : System.Web.UI.Page
    {
        string strcon = ConfigurationManager.ConnectionStrings["sqlconn"].ConnectionString;
// you have to add configuration in name space .
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
            }
        }
code in button click event

        protected void Button1_Click(object sender, EventArgs e)
        {
try
{
            SqlConnection con = new SqlConnection(strcon);
            SqlCommand cmd = new SqlCommand("insert_sp_emp", con);
 //here i passed stored procedure instead ofinsert  query.
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@Name", txt_name.Text);
            cmd.Parameters.AddWithValue("@Description", txt_description.Text);
            cmd.Parameters.AddWithValue("@Department", txt_depart.Text);
            con.Open();
            cmd.ExecuteNonQuery();
       label1.text="Record Inserted Succesfully;
            con.Close();
}
catch(Exception,ex)
{
label1.Text=ex.message;
}

        }
    }
}
in sql server 
 crete table 
and write  procedure for insert query i.e,

create procedure insert_sp_emp(@Name nvarchar(50),@Description nvarchar(50),@Department nvarchr(50))
AS
BEGIN
insert into tablename(Name,Description,Department) values(@Name,@Description,@Department)
END

if you set an identity true no need to mention id as parameter-(@Id int)

Web Config file:

<configuration>
  <connectionStrings>
    <add name="sqlconn" connectionString="Data Source=SYS-2;Initial Catalog=Emp;Integrated Security=True"/>

  </connectionStrings>

So build your application and start debugging then it shown your output like this 




then you have to display the complete record into gridview using asp.net:
in .aspx page:
drag and drop gridview from datbound controls
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
            <Columns>
                <asp:BoundField DataField="Id" HeaderText="Id" />
                <asp:BoundField DataField="Name" HeaderText="Name" />
                <asp:BoundField DataField="Description" HeaderText="Description" />
                <asp:BoundField DataField="Department" HeaderText="Department" />
            </Columns>


        </asp:GridView>

code in .aspx.cs page:
 public void binddata()
        {
            SqlConnection con = new SqlConnection(strcon);
            SqlCommand cmd = new SqlCommand("select* from Emp", con);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            da.Fill(ds);
            GridView1.DataSource = ds;
            GridView1.DataBind();

        }
In button click event  you have to mention 
bindata(); before con.close();//connection close
then build the and debug the code once
then it will be displayed liked this


so it is useful for beginners who are learning asp.net newly
I hope you understand  raise a query you have any doubt about this