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