Tuesday, May 7, 2013

How to Bind,Edit,Update and Delete in Listview in Asp.net(C#,VB)


Introduction: In this post I will explain you how to bind, edit, delete and update the Listview data control in Asp.net.

Description:
I have created a table name STUDENT_DETAIL.
STUDENT_ID
int
STUDENT_NAME
varchar(50)
STUDENT_ADDRESS
varchar(50)
STUDENT_CLASS
varchar(50)

STUDENT_ID is primary key.
Now open the Visual Studio>Go to File>New>Website. Add the Connectionstring in web.config file of website.
<configuration>
       <connectionStrings>
    <add name="connection" connectionString="Data Source=SYS-1F78031ED0A;Initial Catalog=TestBlog;Integrated Security=True"/>
       </connectionStrings>
       <system.web>
        <compilation debug="true" targetFramework="4.0" />
    </system.web>
</configuration>


After that add new web form to website, drag and drop the Listview Data control from Toolbox.
<asp:ListView ID="liststudent" runat="server" DataKeyNames="STUDENT_ID" EmptyDataText="No Data Found"
            onitemediting="liststudent_ItemEditing"
            onitemcanceling="liststudent_ItemCanceling"
            onitemdeleting="liststudent_ItemDeleting"
            onitemupdating="liststudent_ItemUpdating">
                       <LayoutTemplate>
     <table style="margin:0px auto;border:1px solid #c1c1c1;">
  <tr style="background-color:#E5E5FE;font-weight:bold">
   <td align="left"><asp:Label ID="lblstudent" runat="server">Student Name</asp:Label></td>
   <td align="left"><asp:Label ID="lblstudentaddress" runat="server">Student Address</asp:Label></td>
   <td align="left"><asp:Label ID="lblstudentclass" runat="server">Student Class</asp:Label></td>
   <td align="left"><asp:LinkButton ID="LinkButton1" runat="server"></asp:LinkButton></td>
   <td align="left"><asp:LinkButton ID="LinkButton2" runat="server"></asp:LinkButton></td><td><asp:Label ID="lblmesage" runat="server" Text=""></asp:Label></td>
     </tr>
    <tr id="itemPlaceholder" runat="server"></tr>
</LayoutTemplate>
                     <ItemTemplate>
                   
        <tr style="background-color: #E0FFFF; color: #333333;font-style:italic;text-align:center">
       <td align="left"> <asp:Label ID="lblstudentname" runat="server" Text='<%#Eval("STUDENT_NAME")%>'></asp:Label></td>
         <td><asp:Label ID="lbladdress" runat="server" Text='<%#Eval("STUDENT_ADDRESS") %>'></asp:Label></td>
          <td><asp:Label ID="lblclass" runat="server" Text='<%#Eval("STUDENT_CLASS") %>'></asp:Label></td>
          <td><asp:LinkButton ID="lnkedit" runat="server" CommandName="edit">Edit</asp:LinkButton></td>
<td><asp:LinkButton ID="lnkdelete" CommandName="Delete" runat="server" OnClientClick="Are you sure want to Delete this Record?">Delete</asp:LinkButton></td>
</tr>
        </ItemTemplate>
        <EditItemTemplate>
         <tr>
       <td> <asp:TextBox ID="txtstudent" runat="server" Text='<%#Eval("STUDENT_NAME")%>'></asp:TextBox></td>
       <td><asp:TextBox ID="txtstudentaddress" runat="server" Text='<%#Eval("STUDENT_ADDRESS") %>'></asp:TextBox></td>
       <td><asp:TextBox ID="txtstudentclass" runat="server" Text='<%#Eval("STUDENT_CLASS") %>'></asp:TextBox></td>
       <td><asp:LinkButton ID="lnkupdate" runat="server" CommandName="Update">Update</asp:LinkButton></td>
        <td><asp:LinkButton ID="lnkcancel" runat="server" CommandName="cancel">Cancel</asp:LinkButton></td></tr>
                        </EditItemTemplate>
             <EmptyDataTemplate> 
                                 <table border="1">
             <tr style="color:Red;"><td align="center">
                 <asp:Label ID="lblmessage" runat="server" Text=" No Record Available
"></asp:Label></td></tr></table>
                </EmptyDataTemplate>
    
        </asp:ListView>

Now go to .aspx.cs page and add namespace.



using System.Data;
using System.Data.SqlClient;
using System.Configuration;

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ToString());
    protected void Page_Load(object sender, EventArgs e)
    {
        if (con.State == ConnectionState.Closed)
            con.Open();
        if (!IsPostBack)
        {
            bindListview();
        }
    }
    private void bindListview()
    {
        try
        {
            SqlDataAdapter adp = new SqlDataAdapter("select * from STUDENT_DETAIL", con);
            DataTable dt = new DataTable();
            adp.Fill(dt);
            if (dt.Rows.Count > 0)
            {
                liststudent.DataSource = dt;
                liststudent.DataBind();
            }
            else
            {
                liststudent.DataSource = null;
                liststudent.DataBind();
               
            }
        }
        catch (Exception ex)
        {
        }

    }
    protected void liststudent_ItemEditing(object sender, ListViewEditEventArgs e)
    {
        liststudent.EditIndex = e.NewEditIndex;
        bindListview();
    }
    protected void liststudent_ItemCanceling(object sender, ListViewCancelEventArgs e)
    {
        liststudent.EditIndex = -1;
        bindListview();
    }
    protected void liststudent_ItemUpdating(object sender, ListViewUpdateEventArgs e)
    {
        try
        {
            int STUDENT_ID = Convert.ToInt32(liststudent.DataKeys[e.ItemIndex].Value.ToString());
            TextBox txtname = (TextBox)liststudent.Items[e.ItemIndex].FindControl("txtstudent");
            TextBox txtaddress = (TextBox)liststudent.Items[e.ItemIndex].FindControl("txtstudentaddress");
            TextBox txtclass = (TextBox)liststudent.Items[e.ItemIndex].FindControl("txtstudentclass");
            Label lblmessage = (Label)liststudent.Items[e.ItemIndex].FindControl("lblmessage");
            string update = "Update STUDENT_DETAIL set STUDENT_NAME='" + txtname.Text.Trim() + "',STUDENT_ADDRESS='" + txtaddress.Text.Trim() + "',STUDENT_CLASS ='" + txtclass.Text.Trim() + "' where STUDENT_ID=" + STUDENT_ID;
            SqlCommand command = new SqlCommand(update, con);
            command.ExecuteNonQuery();
            Messagebox("Update Record Successfully");
            liststudent.EditIndex = -1;
            bindListview();
        }
        catch (Exception ex)
        {
        }
    }
    protected void liststudent_ItemDeleting(object sender, ListViewDeleteEventArgs e)
    {
        try
        {
            int STUDENT_ID = Convert.ToInt32(liststudent.DataKeys[e.ItemIndex].Value.ToString());
            string delete = "Delete from STUDENT_DETAIL where STUDENT_ID=" + STUDENT_ID;
            SqlCommand command = new SqlCommand(delete, con);
            command.ExecuteNonQuery();
            bindListview();
            Messagebox("Delete Record Successfully");
        }
        catch (Exception ex)
        {
        }
    }
    //To show message
    private void Messagebox(string Message)
    {
        Label lblMessageBox = new Label();

        lblMessageBox.Text =
            "<script language='javascript'>" + Environment.NewLine +
            "window.alert('" + Message + "')</script>";

        Page.Controls.Add(lblMessageBox);

    }

In VB:
Go to .aspx.vb page and add namespace.
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration

Private con As New SqlConnection(ConfigurationManager.ConnectionStrings("connection").ToString())
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If con.State = ConnectionState.Closed Then
            con.Open()
        End If
        If Not IsPostBack Then
            bindListview()
        End If
    End Sub
    Private Sub bindListview()
        Try
            Dim adp As New SqlDataAdapter("select * from STUDENT_DETAIL", con)
            Dim dt As New DataTable()
            adp.Fill(dt)
            If dt.Rows.Count > 0 Then
                liststudent.DataSource = dt
                liststudent.DataBind()
            Else
                liststudent.DataSource = Nothing
                liststudent.DataBind()

            End If
        Catch ex As Exception
        End Try

    End Sub
    Protected Sub liststudent_ItemEditing(ByVal sender As Object, ByVal e As ListViewEditEventArgs)
        liststudent.EditIndex = e.NewEditIndex
        bindListview()
    End Sub
    Protected Sub liststudent_ItemCanceling(ByVal sender As Object, ByVal e As ListViewCancelEventArgs)
        liststudent.EditIndex = -1
        bindListview()
    End Sub
    Protected Sub liststudent_ItemUpdating(ByVal sender As Object, ByVal e As ListViewUpdateEventArgs)
        Try
            Dim STUDENT_ID As Integer = Convert.ToInt32(liststudent.DataKeys(e.ItemIndex).Value.ToString())
            Dim txtname As TextBox = DirectCast(liststudent.Items(e.ItemIndex).FindControl("txtstudent"), TextBox)
            Dim txtaddress As TextBox = DirectCast(liststudent.Items(e.ItemIndex).FindControl("txtstudentaddress"), TextBox)
            Dim txtclass As TextBox = DirectCast(liststudent.Items(e.ItemIndex).FindControl("txtstudentclass"), TextBox)
            Dim lblmessage As Label = DirectCast(liststudent.Items(e.ItemIndex).FindControl("lblmessage"), Label)
            Dim update As String = "Update STUDENT_DETAIL set STUDENT_NAME='" & txtname.Text.Trim() & "',STUDENT_ADDRESS='" & txtaddress.Text.Trim() & "',STUDENT_CLASS ='" & txtclass.Text.Trim() & "' where STUDENT_ID=" & STUDENT_ID
            Dim command As New SqlCommand(update, con)
            command.ExecuteNonQuery()
            Messagebox("Update Record Successfully")
            liststudent.EditIndex = -1
            bindListview()
        Catch ex As Exception
        End Try
    End Sub
    Protected Sub liststudent_ItemDeleting(ByVal sender As Object, ByVal e As ListViewDeleteEventArgs)
        Try
            Dim STUDENT_ID As Integer = Convert.ToInt32(liststudent.DataKeys(e.ItemIndex).Value.ToString())
            Dim delete As String = "Delete from STUDENT_DETAIL where STUDENT_ID=" & STUDENT_ID
            Dim command As New SqlCommand(delete, con)
            command.ExecuteNonQuery()
            bindListview()
            Messagebox("Delete Record Successfully")
        Catch ex As Exception
        End Try
    End Sub
    'To show message
    Private Sub Messagebox(ByVal Message As String)
        Dim lblMessageBox As New Label()

        lblMessageBox.Text = "<script language='javascript'>" + Environment.NewLine & "window.alert('" & Message & "')</script>"

        Page.Controls.Add(lblMessageBox)

    End Sub

Now debug/run the project and check the result.

Is it helpful?

If yes post your comment to admire my work. You can like me on Facebook, Google+, Linkedin and Twitter via hit on Follow us Button and also can get update follow by Email.

No comments:

Post a Comment