How to Maintain Dataset in ViewState

Abstract


Here we will discuss about how to maintain Data set in view state using vb.net.Just drag and drop the one grid view and button control to your web page.

In Aspx.vb



[code]
Imports System.Data
Partial Class _Default
Inherits System.Web.UI.Page
Dim dtrow As DataRow
Dim dstDataSet As DataSet
Public Shared Function GetFieldType(ByVal FieldType As String) As System.Type
Select Case FieldType
Case "int"
Return Type.GetType("System.Int32")
Case "varchar"
Return Type.GetType("System.String")
Case "datetime"
Return Type.GetType("System.DateTime")
Case "float"
Return Type.GetType("System.Double")
End Select
Return Type.GetType("System.Object")
End Function

Public Shared Function DefineDataset(ByVal Field() As String, ByVal FieldType() As String, ByVal PrimaryKey As String) As DataSet
Dim dstDataset As New DataSet
Dim dtTable As New DataTable
Dim i As Integer
For i = 0 To FieldType.Length - 1
dtTable.Columns.Add(New DataColumn(Field(i), GetFieldType(FieldType(i))))
If Field(i) = PrimaryKey Then
dtTable.Constraints.Add("c" & i, dtTable.Columns(i), True)
End If
Next
dstDataset.Tables.Add(dtTable)
Return (dstDataset)
End Function
Public Property GridBindDataSet() As DataSet
Get
If Not (ViewState("GridDataset") Is Nothing) Then
dstDataSet = CType(ViewState("GridDataset"), DataSet)
End If
If dstDataSet Is Nothing Then
dstDataSet = DefineDataset(New String() {"EmpID", "EmpName"}, New String() {"varchar", "varchar"}, "")
ViewState.Add("GridDataset", dstDataSet)
End If
Return dstDataSet
End Get

Set(ByVal value As DataSet)
dstDataSet = value
If Not (ViewState("GridDataset") Is Nothing) Then
ViewState("GridDataset") = dstDataSet
Else
ViewState.Add("GridDataset", dstDataSet)
End If
End Set
End Property
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
Dim drwRow As DataRow = GridBindDataSet.Tables(0).NewRow()
drwRow("EmpID") = ""
drwRow("EmpName") = ""
GridBindDataSet.Tables(0).Rows.Add(drwRow)
GridView1.DataSource = GridBindDataSet
GridView1.DataBind()
End If
End Sub

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click

Dim drwRow As DataRow = GridBindDataSet.Tables(0).NewRow()
drwRow("EmpID") = ""
drwRow("EmpName") = ""
GridBindDataSet.Tables(0).Rows.Add(drwRow)
GridView1.DataSource = GridBindDataSet
GridView1.DataBind()
End Sub
End Class

[/code]

No comments:

Post a Comment

Plz Share your comments...