How to Bind, Edit, Delete, Paging and Update in Detailsview in Asp.net(C#, VB)? | ASPMANTRA | Asp.Net,MVC,AngularJs,Jquery,Javascript,Sql Server AND WCF snippets and tutorial

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


Introduction: In this post I will explain you how to bind, edit, delete and update the Detailsview 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 Detailsview Data control from Toolbox.
<asp:DetailsView ID="studentdetailview" runat="server" CellPadding="4"
            Height="50px" Width="400px" AutoGenerateRows="False" DataKeyNames="STUDENT_ID"
            AllowPaging="True"
            onpageindexchanging="studentdetailview_PageIndexChanging"
            onitemupdating="studentdetailview_ItemUpdating"
            onmodechanging="studentdetailview_ModeChanging"
            onitemdeleting="studentdetailview_ItemDeleting">
             <FieldHeaderStyle BackColor="#E9ECF1" Font-Bold="True" />
             <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
            <CommandRowStyle BackColor="#E2DED6" Font-Bold="True" />
            <RowStyle BackColor="#e8d5f1" ForeColor="#333333" />
            <FieldHeaderStyle BackColor="#E9ECF1" Font-Bold="True" />
            <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
            <Fields>
                <asp:TemplateField HeaderText="Student Name">
                    <EditItemTemplate>
                        <asp:TextBox ID="txtstudentname" runat="server" Text='<%# Eval("STUDENT_NAME") %>'></asp:TextBox>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="lblstudentname" runat="server" Text='<%# Eval("STUDENT_NAME") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Student Address">
                    <EditItemTemplate>
                        <asp:TextBox ID="txtstudentaddress" runat="server" Text='<%# Eval("STUDENT_ADDRESS") %>'></asp:TextBox>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="lblstudentaddress" runat="server" Text='<%# Eval("STUDENT_ADDRESS") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Student Class">
                    <EditItemTemplate>
                        <asp:TextBox ID="txtstudentclass" runat="server" Text='<%# Eval("STUDENT_CLASS") %>'></asp:TextBox>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="lblstudentclass" runat="server" Text='<%# Eval("STUDENT_CLASS") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Editing">
                <EditItemTemplate>
<asp:LinkButton ID="LinkButton6" runat="server" CommandName="update">Update</asp:LinkButton>
<asp:LinkButton ID="LinkButton7" runat="server" CommandName="cancel">Cacel</asp:LinkButton>
</EditItemTemplate>
                <ItemTemplate>
                <asp:LinkButton ID="LinkButton1" runat="server" CommandName="edit">Edit</asp:LinkButton>
<asp:LinkButton ID="LinkButton2" runat="server" CommandName="delete">Delete</asp:LinkButton>
                </ItemTemplate>
                </asp:TemplateField>
                          
                            </Fields>
                                               </asp:DetailsView>
After that go to .aspx.cs page and add namespace.

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

Now write code to bind Detailsview and its properties.
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)
        {
            Binddetailsview();
        }
    }
    private void Binddetailsview()
    {
        try
        {
            SqlDataAdapter adp = new SqlDataAdapter("Select * from STUDENT_DETAIL", con);
            DataTable dt = new DataTable();
            adp.Fill(dt);
            if (dt.Rows.Count > 0)
            {
                studentdetailview.DataSource = dt;
                studentdetailview.DataBind();
            }
            else
            {
                dt.Rows.Add(dt.NewRow());
                studentdetailview.DataSource = dt;
                studentdetailview.DataBind();
                int columncount = studentdetailview.Rows[0].Cells.Count;
                studentdetailview.Rows[0].Cells.Clear();
                studentdetailview.Rows[0].Cells.Add(new TableCell());
                studentdetailview.Rows[0].Cells[0].ColumnSpan = columncount;
                studentdetailview.Rows[0].Cells[0].Text = "No Records Available";
            }
        }
        catch (Exception ex)
        {
        }
    }
    protected void studentdetailview_PageIndexChanging(object sender, DetailsViewPageEventArgs e)
    {
        studentdetailview.PageIndex = e.NewPageIndex;
        Binddetailsview();
    }
protected void studentdetailview_ItemUpdating(object sender, DetailsViewUpdateEventArgs e)
    {
        try
        {
           
            //int STUDENT_ID = Convert.ToInt32(studentdetailview.DataKey).ToString());
            DataKey key = studentdetailview.DataKey;
            TextBox txtname = (TextBox)studentdetailview.Rows[1].FindControl("txtstudentname");
            TextBox txtaddress = (TextBox)studentdetailview.Rows[2].FindControl("txtstudentaddress");
            TextBox txtclass = (TextBox)studentdetailview.Rows[3].FindControl("txtstudentclass");
            string update = "Update STUDENT_DETAIL set STUDENT_NAME='" + txtname.Text.Trim() + "',STUDENT_ADDRESS='" + txtaddress.Text.Trim() + "',STUDENT_CLASS='"+txtclass.Text.Trim()+"' where STUDENT_ID ="+key.Value.ToString();
            SqlCommand cmd = new SqlCommand(update, con);
            cmd.ExecuteNonQuery();
            studentdetailview.ChangeMode(DetailsViewMode.ReadOnly);
            Binddetailsview();
         }
        catch (Exception ex)
        {
        }
    }
    protected void studentdetailview_ModeChanging(object sender, DetailsViewModeEventArgs e)
    {
      
            studentdetailview.ChangeMode(e.NewMode);
            Binddetailsview();
      
    }

    protected void studentdetailview_ItemDeleting(object sender, DetailsViewDeleteEventArgs e)
    {
        try
        {
            DataKey key = studentdetailview.DataKey;
            string Delete = "Delete From STUDENT_DETAIL where STUDENT_ID=" + key.Value.ToString();
            SqlCommand cmd = new SqlCommand(Delete, con);
            cmd.ExecuteNonQuery();
            studentdetailview.ChangeMode(DetailsViewMode.ReadOnly);
            Binddetailsview();
        }
        catch (Exception ex)
        {
        }
    }

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

Now write code to bind Detailsview and its properties.
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
            Binddetailsview()
        End If
    End Sub
  
    Private Sub Binddetailsview()
        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
                studentdetailview.DataSource = dt
                studentdetailview.DataBind()
            Else
                dt.Rows.Add(dt.NewRow())
                studentdetailview.DataSource = dt
                studentdetailview.DataBind()
                Dim columncount As Integer = studentdetailview.Rows(0).Cells.Count
                studentdetailview.Rows(0).Cells.Clear()
                studentdetailview.Rows(0).Cells.Add(New TableCell())
                studentdetailview.Rows(0).Cells(0).ColumnSpan = columncount
                studentdetailview.Rows(0).Cells(0).Text = "No Records Available"
            End If
        Catch ex As Exception
        End Try
    End Sub


    Protected Sub studentdetailview_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DetailsViewPageEventArgs) Handles studentdetailview.PageIndexChanging
        studentdetailview.PageIndex = e.NewPageIndex
        Binddetailsview()
    End Sub
    Protected Sub studentdetailview_ItemUpdating(ByVal sender As Object, ByVal e As DetailsViewUpdateEventArgs)
        Try

            'int STUDENT_ID = Convert.ToInt32(studentdetailview.DataKey).ToString());
            Dim key As DataKey = studentdetailview.DataKey
            Dim txtname As TextBox = DirectCast(studentdetailview.Rows(1).FindControl("txtstudentname"), TextBox)
            Dim txtaddress As TextBox = DirectCast(studentdetailview.Rows(2).FindControl("txtstudentaddress"), TextBox)
            Dim txtclass As TextBox = DirectCast(studentdetailview.Rows(3).FindControl("txtstudentclass"), TextBox)
            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 =" & key.Value.ToString()
            Dim cmd As New SqlCommand(update, con)
            cmd.ExecuteNonQuery()
            studentdetailview.ChangeMode(DetailsViewMode.[ReadOnly])
            Binddetailsview()
        Catch ex As Exception
        End Try
    End Sub
    Protected Sub studentdetailview_ModeChanging(ByVal sender As Object, ByVal e As DetailsViewModeEventArgs)

        studentdetailview.ChangeMode(e.NewMode)
        Binddetailsview()

    End Sub

    Protected Sub studentdetailview_ItemDeleting(ByVal sender As Object, ByVal e As DetailsViewDeleteEventArgs)
        Try
            Dim key As DataKey = studentdetailview.DataKey
            Dim Delete As String = "Delete From STUDENT_DETAIL where STUDENT_ID=" & key.Value.ToString()
            Dim cmd As New SqlCommand(Delete, con)
            cmd.ExecuteNonQuery()
            studentdetailview.ChangeMode(DetailsViewMode.[ReadOnly])
            Binddetailsview()
        Catch ex As Exception
        End Try
    End Sub

Debug the Application 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.

Post a Comment

[blogger]

MKRdezign

Contact Form

Name

Email *

Message *

Powered by Blogger.
Javascript DisablePlease Enable Javascript To See All Widget