C# Tutorials and offshore development in India
    Tutorials   Resources   Forum   Reviews   Communities   Interview   Jobs   Projects   Training   Your Ad Here    
Silverlight Games | Mentor | Code Converter | Articles | Code Factory | Computer Jokes | Members | Peer Appraisal | IT Companies | Bookmarks | Polls | Revenue Sharing | Lobby | Gift Shop |


Prizes & Awards
My Profile



Active Members
TodayLast 7 Days more...






Resources » Code Snippets » ASP.NET WebForms »

Dealing with Detailsview control through coding


Posted Date: 29 Oct 2009    Resource Type: Code Snippets    Category: ASP.NET WebForms
Author: NeetuMember Level: Diamond    
Rating: 1 out of 5Points: 5



Insertion updation and deletion of data in detailview through coding


Page1.aspx



<%@ Page Language="VB" AutoEventWireup="false" CodeFile="DetailsViewThroughCoding.aspx.vb" Inherits="Default2" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body bgcolor="burlywood" style="font-family: Times New Roman">
<form id="form1" runat="server">
<div style="text-align: center">
<br />
<span style="font-size: 24pt; color: #ffcc99"><span style="color: #663300"><span
style="font-family: Courier New"><span style="font-size: 32pt;"><span style="text-decoration: underline">
<strong><em>
Details View Through Coding<br />
<br />
</em></strong></span><span style="font-size: 14pt; color: #000000; font-family: Times New Roman">
Displays the values of a single record from a data source in a table, where each
data row represents a field of the record. The </span><a href="T_System_Web_UI_WebControls_DetailsView.htm">
<span style="font-size: 14pt; font-family: Times New Roman">DetailsView</span></a><span
style="font-size: 14pt; color: #000000; font-family: Times New Roman"> control allows
you to edit, delete, and insert records.<br />
</span></span></span></span></span></div>
<asp:DetailsView ID="DetailsView1" runat="server" AllowPaging="True"
AutoGenerateRows="False" Height="50px" Width="633px" BackColor="#DEBA84" BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px" CellPadding="3" CellSpacing="2" Font-Underline="False">
<FooterTemplate>
<asp:LinkButton ID="NewButton" runat="server" CommandName="New" Visible="False" >New</asp:LinkButton> <asp:LinkButton
ID="InsertButton" runat="server" CommandName="Insert">Insert</asp:LinkButton>
<asp:LinkButton ID="EditButton" runat="server" CommandName="Edit"
Width="24px" Visible="False">Edit</asp:LinkButton>
<asp:LinkButton ID="UpdateButton" runat="server" CommandName="Update" Visible="False">Update</asp:LinkButton>
<asp:LinkButton ID="CancelButton" runat="server" CommandName="Cancel">Cancel</asp:LinkButton>
<asp:LinkButton ID="DeleteButton" runat="server" CommandName="Delete" Visible="False">Delete</asp:LinkButton>
</FooterTemplate>
<Fields>
<asp:TemplateField HeaderText="Roll No.">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("rollno") %>'></asp:TextBox>
</EditItemTemplate>
<InsertItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("rollno") %>'></asp:TextBox>
<br />
</InsertItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("rollno") %>'></asp:Label>
<br />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<EditItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("name") %>'></asp:TextBox>
</EditItemTemplate>
<InsertItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("name") %>'></asp:TextBox>
</InsertItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Address">
<EditItemTemplate>
<asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("address") %>'></asp:TextBox>
</EditItemTemplate>
<InsertItemTemplate>
<asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("address") %>'></asp:TextBox>
</InsertItemTemplate>
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Bind("address") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Phone no">
<EditItemTemplate>
<asp:TextBox ID="TextBox4" runat="server" Text='<%# Bind("phoneno") %>'></asp:TextBox>
</EditItemTemplate>
<InsertItemTemplate>
<asp:TextBox ID="TextBox4" runat="server" Text='<%# Bind("phoneno") %>'></asp:TextBox>
</InsertItemTemplate>
<ItemTemplate>
<asp:Label ID="Label4" runat="server" Text='<%# Bind("phoneno") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Fields>
<FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
<EditRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" />
<RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
<PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
<HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" />
</asp:DetailsView>
<br />



</form>
</body>
</html>

page1.aspx.vb



Imports System.Data.OleDb
Partial Class Default2
Inherits System.Web.UI.Page
Dim da As New OleDbDataAdapter
Dim cmd As New OleDbCommand
Dim dt As New System.Data.DataTable
Dim con As New OleDbConnection
Dim str As New System.Text.StringBuilder
Dim t As String
Dim i As Integer

'Through property here I am creating the database connection
Public ReadOnly Property constr()
Get
str.Append("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=")
str.Append(AppDomain.CurrentDomain.BaseDirectory)
str.Append("app_data/Yogita.mdb")
str.Append(";Persist Security Info=False")
'MsgBox(str.ToString)
con.ConnectionString = str.ToString
Return con
End Get
End Property
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
'Page.MaintainScrollPositionOnPostBack is a property used to maintain the scroll position after the postback.
Page.MaintainScrollPositionOnPostBack = True

If Not Page.IsPostBack Then
'showtable() is user defined method that will fill the data in table and store it in dt
dt = showtable()
'bind() is user defined method that will bind the data with the detailsview.
Call bind()
End If

End Sub
Sub bind()
dt = showtable()
'If detailsview is binded with any datasource so remove that by using nothing keyword
DetailsView1.DataSource = Nothing
'set the datatable
DetailsView1.DataSource = dt
'Binding the data with detailsview
DetailsView1.DataBind()
'AllowPaing that means details view has different no. of pages depending on the number of records.
DetailsView1.AllowPaging = True

'CurrentMode will indicate whether the user want update, delete or insert data in the database.
'In Edit mode new,edit,delete,insert buttons will not be visible only update and cancel will be visible.
If DetailsView1.CurrentMode = DetailsViewMode.Edit Then
DetailsView1.FindControl("newbutton").Visible = False
DetailsView1.FindControl("editbutton").Visible = False
DetailsView1.FindControl("deletebutton").Visible = False
DetailsView1.FindControl("insertbutton").Visible = False
DetailsView1.FindControl("updatebutton").Visible = True
DetailsView1.FindControl("cancelbutton").Visible = True

End If
'In Insert mode new,edit,delete,update buttons will not be visible only insert and cancel will be visible.
If DetailsView1.CurrentMode = DetailsViewMode.Insert Then

DetailsView1.FindControl("newbutton").Visible = False
DetailsView1.FindControl("editbutton").Visible = False
DetailsView1.FindControl("deletebutton").Visible = False
DetailsView1.FindControl("updatebutton").Visible = False
DetailsView1.FindControl("cancelbutton").Visible = True
DetailsView1.FindControl("insertbutton").Visible = True
End If
'In readonly mode new,edit,delete buttons will be visible and insert, update and cancel will not be visible.
If DetailsView1.CurrentMode = DetailsViewMode.ReadOnly Then
DetailsView1.FindControl("newbutton").Visible = True
DetailsView1.FindControl("editbutton").Visible = True
DetailsView1.FindControl("deletebutton").Visible = True
DetailsView1.FindControl("updatebutton").Visible = False
DetailsView1.FindControl("cancelbutton").Visible = False
DetailsView1.FindControl("insertbutton").Visible = False
End If
End Sub
Function showtable() As System.Data.DataTable
'creating the object of system datatable.
Dim dt1 As New System.Data.DataTable
cmd = Nothing
cmd = New OleDbCommand
da = Nothing
'Through oledbcommand and oledbDataAdapter filling the data in dataTable.
da = New OleDbDataAdapter
dt1 = New System.Data.DataTable
cmd.CommandText = "studentdetails"
cmd.CommandType = Data.CommandType.TableDirect
'If connection is opened then first closed it and again reopen it.
If con.State = Data.ConnectionState.Open Then
con.Close()
End If
cmd.Connection = constr
da = New OleDbDataAdapter(cmd)
da.Fill(dt1)
Return dt1
End Function
Protected Sub DetailsView1_ItemCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DetailsViewCommandEventArgs) Handles DetailsView1.ItemCommand
'CommandName is cancel then it will be in readonly mode.
If e.CommandName = "Cancel" Then
DetailsView1.ChangeMode(DetailsViewMode.ReadOnly)
bind()
End If
End Sub
Protected Sub DetailsView1_ItemDeleting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DetailsViewDeleteEventArgs) Handles DetailsView1.ItemDeleting
Dim r As Integer
'While deleting the data from detailsview first we will find the id of row by fetching data from the label1
r = Val((CType(DetailsView1.FindControl("Label1"), Label).Text))

'through oledbcommand we will create the delete query.
Dim cmd1 As New OleDbCommand
cmd1.CommandText = "Delete from studentdetails where rollno=" & r
cmd1.Connection = constr
If con.State = Data.ConnectionState.Broken Or con.State = Data.ConnectionState.Open Then
con.Close()
End If
con.Open()
'After opening the connection using ExecuteNonQuery we will fire the query and it will return number of rows effected in the database.
If cmd1.ExecuteNonQuery Then
MsgBox("Record Deleted successfully")
End If
con.Close()
bind()
End Sub
Protected Sub DetailsView1_ItemInserting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DetailsViewInsertEventArgs) Handles DetailsView1.ItemInserting
Dim no As Integer
Dim name As String
Dim add As String
Dim pno As Integer

'While inserting the data in the database using details view we have to first get the data from all the controls using findcontrol.
no = (CType(DetailsView1.FindControl("Textbox1"), TextBox).Text)
name = (CType(DetailsView1.FindControl("Textbox2"), TextBox).Text)
add = (CType(DetailsView1.FindControl("Textbox3"), TextBox).Text)
pno = (CType(DetailsView1.FindControl("Textbox4"), TextBox).Text)

Dim s As New System.Text.StringBuilder
'Here using string builder we are creating the insert statement.
s.Append("insert into studentdetails values (")
s.Append(no)
s.Append(",'")
s.Append(name)
s.Append("','")
s.Append(add)
s.Append("',")
s.Append(pno)
s.Append(")")

Dim cmd1 As New OleDbCommand
cmd1.CommandText = s.ToString
cmd1.Connection = constr
If con.State = Data.ConnectionState.Broken Or con.State = Data.ConnectionState.Open Then
con.Close()
End If
con.Open()
If cmd1.ExecuteNonQuery Then
MsgBox("Record Inserted successfully")
End If
DetailsView1.ChangeMode(DetailsViewMode.ReadOnly)
con.Close()
bind()

End Sub

Protected Sub DetailsView1_ItemUpdating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DetailsViewUpdateEventArgs) Handles DetailsView1.ItemUpdating
Dim no As Integer
Dim name As String
Dim add As String
Dim pno As Integer
'same as insertion of data
no = (CType(DetailsView1.FindControl("Textbox1"), TextBox).Text)
name = (CType(DetailsView1.FindControl("Textbox2"), TextBox).Text)
add = (CType(DetailsView1.FindControl("Textbox3"), TextBox).Text)
pno = (CType(DetailsView1.FindControl("Textbox4"), TextBox).Text)

Dim s As New System.Text.StringBuilder

s.Append("update studentdetails set name= ")
s.Append("'")
s.Append(name)
s.Append("',address='")
s.Append(add)
s.Append("',phoneno=")
s.Append(pno)
s.Append(" where rollno=")
s.Append(no)
'MsgBox(s.ToString)
Dim cmd1 As New OleDbCommand
cmd1.CommandText = s.ToString
cmd1.Connection = constr
If con.State = Data.ConnectionState.Broken Or con.State = Data.ConnectionState.Open Then
con.Close()
End If
con.Open()
If cmd1.ExecuteNonQuery Then
MsgBox("Record Updated successfully")
End If
DetailsView1.ChangeMode(DetailsViewMode.ReadOnly)
con.Close()
bind()
End Sub
Protected Sub DetailsView1_ModeChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DetailsViewModeEventArgs) Handles DetailsView1.ModeChanging
'New Data
If e.NewMode = DetailsViewMode.Insert Then
DetailsView1.ChangeMode(DetailsViewMode.Insert)
DetailsView1.AllowPaging = False
End If
'Edit Mode
If e.NewMode = DetailsViewMode.Edit Then
DetailsView1.ChangeMode(DetailsViewMode.Edit)
'bind()
DetailsView1.AllowPaging = False
End If
bind()
End Sub
Protected Sub DetailsView1_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DetailsViewPageEventArgs) Handles DetailsView1.PageIndexChanging
'To change the page of detailsview
DetailsView1.PageIndex = Val(e.NewPageIndex)
bind()
End Sub

End Class


regards
Neetu




Responses


No responses found. Be the first to respond and make money from revenue sharing program.

Feedbacks      
Popular Tags   What are tags ?   Search Tags  
Sign In to add tags.
Dealing with Detailsview Controls  .  

Post Feedback


This is a strictly moderated forum. Only approved messages will appear in the site. Please use 'Spell Check' in Google toolbar before you submit.
You must Sign In to post a response.
Next Resource: Maintaining state using context
Previous Resource: Send email from gmail account in asp.net
Return to Discussion Resource Index
Post New Resource
Category: ASP.NET WebForms


Post resources and earn money!
 
More Resources



dotNet Slackers

About Us    Contact Us    Privacy Policy    Terms Of Use