ASP.NET Formview & GridView Coltrol. Insert, Update, Paging And Delete

<ItemTemplate> <InsertItemTemplate> </EditItemTemplate> With Formview & Gridview

Here is the FULL CODE if you ever want to use a FormView Control / GridView Control for view/insert/update/Paging. Click on this link to see how will the output of this code look like.

http://www.knowlegezone.com/images/cview.gif

Please note code below if for tutorial purpose only, you might ned to make it more secure/error free in production. Please post your comments below if you have any questions.


ASPX PAGE:

<%@ Control Language="vb" AutoEventWireup="false" CodeBehind="FormViewControl.ascx.vb" Inherits="Controls.FormViewControl" %>

<h2>Form View </h2>

<asp:FormView DataKeyNames="id" runat=server ID="myFrmView" AllowPaging=true>

    <ItemTemplate>
        Name: <asp:Label runat=server Text='<%# Bind("name") %>' ID="cName"></asp:Label><br />
        Age: <asp:Label runat=server Text='<%# Bind("age") %>' ID="cAge"></asp:Label><br />
        <asp:Button CommandName="StartEdit" Text="Edit This" ID="EditFrm" runat=server />
        <asp:Button CommandName="StartInsert" Text="Add New" ID="InsertFrm" runat=server />
    </ItemTemplate>
   
    <EditItemTemplate>
                Name: <asp:TextBox runat=server Text='<%# Bind("name") %>' ID="cName"></asp:Textbox><br />
                Age: <asp:Textbox runat=server Text='<%# Bind("age") %>' ID="cAge"></asp:Textbox><br />
                <asp:Button CommandName="EditThis" Text="Edit This" ID="EditFrm" runat=server />
    </EditItemTemplate>
   
    <InsertItemTemplate>
                    Name: <asp:TextBox runat=server ID="cName"></asp:Textbox><br />
                    Age: <asp:Textbox runat=server  ID="cAge"></asp:Textbox><br />
                  <asp:Button CommandName="InsertThis" Text="Save" ID="SaveFrm" runat=server />
    </InsertItemTemplate>
   


</asp:FormView>

<br />
<hr />
<br />

<h2>Grid View</h2>

<asp:GridView DataKeyNames="id" runat=server ID="GrdVw" AutoGenerateColumns=false>

 

    <Columns>
   
        <asp:CommandField HeaderText="Edit This" ShowEditButton=true />
        <asp:CommandField HeaderText="Remove" ShowDeleteButton=true />
       
       
        <asp:TemplateField HeaderText="Name">
       
            <ItemTemplate>
                   <asp:Label runat=server Text='<%# Bind("name") %>' ID="cName"></asp:Label><br />
            </ItemTemplate>           
            <EditItemTemplate>
                    <asp:TextBox runat=server Text='<%# Bind("name") %>' ID="cName"></asp:Textbox><br />
            </EditItemTemplate>
       </asp:TemplateField>
            
        <asp:TemplateField HeaderText="Age">
            <ItemTemplate>
                    <asp:Label runat=server Text='<%# Bind("age") %>' ID="cAge"></asp:Label><br />
            </ItemTemplate>
            <EditItemTemplate>
                    <asp:Textbox runat=server Text='<%# Bind("age") %>' ID="cAge"></asp:Textbox>
            </EditItemTemplate>
         </asp:TemplateField>
       
      
   
    </Columns>


</asp:GridView>

 

 

CODE BEHIND:

 

Imports System.Data.SqlClient
Imports System.Data

Partial Public Class FormViewControl
    Inherits System.Web.UI.UserControl

 

        If Not Page.IsPostBack Then
            Call BringData(0) ' Bind FormView
            Call BringData(1) ' Bind GridView
        End If


    Public Sub BringData(ByVal ctrl As Integer)

        Dim cmd As SqlDataAdapter
        Dim con As SqlConnection
        Dim dt As DataTable

        con = New SqlConnection(util.ConString)
        cmd = New SqlDataAdapter("Select * From Profile", con)

 

        Try
            con.Open()
            dt = New DataTable("Profile")
            cmd.Fill(dt)

            If ctrl = 0 Then
                myFrmView.DataSource = dt
                myFrmView.DataBind()
            End If

            If ctrl = 1 Then
                GrdVw.DataSource = dt
                GrdVw.DataBind()
            End If


        Catch ex As Exception
            MsgBox(ex.Message)
        End Try

    End Sub


    Private Sub myFrmView_ItemCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.FormViewCommandEventArgs) Handles myFrmView.ItemCommand

        Dim cmd As SqlCommand
        Dim con As SqlConnection

        con = New SqlConnection(util.ConString)

 

        If e.CommandName = "StartEdit" Then
            myFrmView.ChangeMode(FormViewMode.Edit)
            Call Me.BringData(0)
        ElseIf e.CommandName = "StartInsert" Then
            myFrmView.ChangeMode(FormViewMode.Insert)
        ElseIf e.CommandName = "EditThis" Then
            Dim name As String = CType(myFrmView.FindControl("cName"), TextBox).Text
            Dim age As String = CType(myFrmView.FindControl("cage"), TextBox).Text
            con.Open()
            cmd = New SqlCommand("Update Profile Set [name] = '" & name & "', age = '" & age & "' Where [id]='" & myFrmView.DataKey.Value & "'", con)
            cmd.ExecuteNonQuery()
        ElseIf e.CommandName = "InsertThis" Then
            Dim name As String = CType(myFrmView.FindControl("cName"), TextBox).Text
            Dim age As String = CType(myFrmView.FindControl("cage"), TextBox).Text
            con.Open()
            cmd = New SqlCommand("Insert into profile(name,age) Values('" & name & "','" & age & "')", con)
            cmd.ExecuteNonQuery()

            Call BringData(1) ' if you want to show the Recently Added user to GridView

        End If

    End Sub

    Private Sub myFrmView_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.FormViewPageEventArgs) Handles myFrmView.PageIndexChanging
        myFrmView.PageIndex = e.NewPageIndex
        Call Me.BringData(0)
    End Sub

    Private Sub GrdVw_RowCancelingEdit(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCancelEditEventArgs) Handles GrdVw.RowCancelingEdit
        GrdVw.EditIndex = -1
        Call Me.BringData(1)
    End Sub

    Private Sub GrdVw_RowDeleting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewDeleteEventArgs) Handles GrdVw.RowDeleting
        Dim cmd As SqlCommand
        Dim con As SqlConnection

        con = New SqlConnection(util.ConString)
        con.Open()

        cmd = New SqlCommand("Delete From Profile Where [id] = '" & GrdVw.DataKeys(e.RowIndex).Value & "'", con)
        cmd.ExecuteNonQuery()

        Call Me.BringData(0)
        Call Me.BringData(1)
    End Sub

    Private Sub GrdVw_RowEditing(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewEditEventArgs) Handles GrdVw.RowEditing

        GrdVw.EditIndex = e.NewEditIndex
        Call Me.BringData(1)

    End Sub

    Private Sub GrdVw_RowUpdating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewUpdateEventArgs) Handles GrdVw.RowUpdating

        Dim cmd As SqlCommand
        Dim con As SqlConnection

        con = New SqlConnection(util.ConString)

        Dim RowinDex As TableCell
        RowinDex = GrdVw.Rows(e.RowIndex).Cells(0)

        Dim iname As String = CType(RowinDex.FindControl("cName"), TextBox).Text
        Dim iage As String = CType(RowinDex.FindControl("cAge"), TextBox).Text

        con.Open()
        cmd = New SqlCommand("Update Profile Set [name] = '" & iname & "', age='" & iage & "' Where [id]='" & GrdVw.DataKeys(e.RowIndex).Value & "'", con)
        cmd.ExecuteNonQuery()


    End Sub
End Class


 

Posted by:

Comments History


by: on
Code for Gridview's Paging should be. Private Sub GrdVw_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) Handles GrdVw.PageIndexChanging GrdVw.PageIndex = e.NewPageIndex Call Me.BringData(1) End Sub
 
by: on
Finally someone who shows something usefull. Thank u very much!
 
by: on
good solutions
 
by: on
I think,This solution is good.I am going to impliment it.
 
by: on
fine.it's good for learners.
 
by: on
good
 
by: on
try this link for simple insert,update and delete in GridView Control without writing a single piece of code in C# or VB http://vijayvigneshonflex.blogspot.com/p/how-to-do-insertupdatedelete-and-select.html
 
by: on
i am getting an error on con.open() it says as: "sqlexception was handled by user code" here is my code: protected void btnadd_Click(object sender, EventArgs e) { SqlConnection con = new SqlConnection (@"Data Source=.\SQLEXPRESS; AttachDbFilename=C:\Documents and Settings\khushboo\My Documents\Visual Studio 2010\WebSites\Ksms1\App_Data\sms.mdf"); string str; str = "insert into contact(name,mobile_no) values(" + txtname.Text + "," + txtno.Text + ")"; SqlCommand cmd = new SqlCommand(str,con); con.Open(); //open connection cmd.ExecuteNonQuery(); lblmsg.Text+= "contact saved"; lblmsg.Visible = true; con.Close(); } this code just adds a contact name and mobile no in the table named contact. please help me out of this
 
by: on
try this SQL... str = "insert into contact(name,mobile_no) values("+ txtname.Text +","+ txtno.Text +")";
 
by: on
If you want to insert values into a text field, you should surround it by quotes like this: str = "insert into contact (name, mobile_no) values (" + txtname.Text + "," + txtno.Text + ")";
 
by: on
I see the quotes got lost after inserting the post. there should be a single quote after values( then before and after the comma in "," and before the last ). I will try to confuse the system and get them in anyway: str = "insert into contact (name, mobile_no) values (" + txtname.Text + "," + txtno.Text + ")";
 
by: on
I am confused. I do not see code for the fv_ModeChanging event, fv_ItemUpdated, fv_ItemInserted, etc. Yet the formview will not run without these events. Other places (i.e. for detailsviews) indicated that changes are required to tgake place in the _ModeChanging event. So why is that not the case here?
 
by: on
i want to design formview as payment reciept of any content please give the screen shots with code to understand more.send me reply on my id 1001.vishal@gmail.com
 
by: on

a simple tutorial on asp.net gridview

http://asp.net-informations.com/gridview/asp-gridview.htm

Warner

 

Name :  

Email :  

Comment Below