在ASP.NET GridView中使用临时数据
使用仅ASP.NET中的临时数据构建具有Gridview的测试页
作者
所以您可能会遇到使用DataGrid的需要,但不希望在每次更改时不断更新数据库。
幸运的是,您可以将所有这些数据存储在会话添加/删除行中,并在客户端和服务器之间传递,而不用触摸数据库。
我不会深入科学,MSDN上有这样的文章。首先,加载一个新的Webform,你将需要添加一个DropDownList,GridView和两个按钮,一个作为假装上传到DB,另一个将用户添加到我们的GridView中。
我已经在我的系统上运行了这一切,所以代码应该直接复制和粘贴,尝试添加每个部分,以便您可以看到如何构建它。
HTML
<div>
<asp:DropDownList ID="UserAvailable" runat="server" Width="200px">
<asp:ListItem Text="Gavin Clayton" Value="1"><asp:ListItem>
<asp:ListItem Text="Sai Gangu" Value="2"><asp:ListItem>
<asp:ListItem Text="Mervin Pereira" Value="3"><asp:ListItem>
<asp:DropDownList>
<asp:Button ID="AddUser" runat="server" Text="Add User" />
<div>
<div>
<asp:GridView ID="UsersForSignOffList" runat="server" AutoGenerateColumns="False" DataKeyNames="ID" GridLines="None" BorderStyle="None" CssClass="DocsGrid">
<AlternatingRowStyle CssClass="alt" />
<Columns>
<asp:BoundField DataField="UserName" HeaderText="Name" SortExpression="UserName" />
<asp:CommandField ShowDeleteButton="True">
<ItemStyle Width="125px" />
<asp:CommandField>
<Columns>
<HeaderStyle BackColor="#CCCCCC" />
<RowStyle CssClass="Grid" />
<asp:GridView>
<div>
<div>
<asp:Button ID="UploadTable" runat="server" Text="Upload" />
<div>
<asp:DropDownList ID="UserAvailable" runat="server" Width="200px">
<asp:ListItem Text="Gavin Clayton" Value="1"><asp:ListItem>
<asp:ListItem Text="Sai Gangu" Value="2"><asp:ListItem>
<asp:ListItem Text="Mervin Pereira" Value="3"><asp:ListItem>
<asp:DropDownList>
<asp:Button ID="AddUser" runat="server" Text="Add User" />
<div>
<div>
<asp:GridView ID="UsersForSignOffList" runat="server" AutoGenerateColumns="False" DataKeyNames="ID" GridLines="None" BorderStyle="None" CssClass="DocsGrid">
<AlternatingRowStyle CssClass="alt" />
<Columns>
<asp:BoundField DataField="UserName" HeaderText="Name" SortExpression="UserName" />
<asp:CommandField ShowDeleteButton="True">
<ItemStyle Width="125px" />
<asp:CommandField>
<Columns>
<HeaderStyle BackColor="#CCCCCC" />
<RowStyle CssClass="Grid" />
<asp:GridView>
<div>
<div>
<asp:Button ID="UploadTable" runat="server" Text="Upload" />
<div>
作者
首先我们声明表,我们将在页面加载中调用这个表
VB
Private Function CreateTable() As DataTable
'Add a user column
Dim dt As DataTable = New DataTable
Dim column As DataColumn
column = New DataColumn()
column.DataType = System.Type.GetType("System.Int32")
column.ColumnName = "UserID"
column.ReadOnly = False
column.Unique = True
dt.Columns.Add(column)
'add a user name column
column = New DataColumn()
column.DataType = System.Type.GetType("System.String")
column.ColumnName = "UserName"
column.ReadOnly = False
column.Unique = False
dt.Columns.Add(column)
'Add a unique column with its own unique id (for delete function)
column = New DataColumn()
column.DataType = System.Type.GetType("System.Int32")
column.ColumnName = "ID"
column.ReadOnly = False
column.Unique = True
column.AutoIncrement = True
column.AutoIncrementSeed = 1
dt.Columns.Add(column)
'add primary key (first key) on column ID
Dim PrimaryKeyColumns(0) As DataColumn
PrimaryKeyColumns(0) = dt.Columns("ID")
dt.PrimaryKey = PrimaryKeyColumns
Return dt
End Function
'Add a user column
Dim dt As DataTable = New DataTable
Dim column As DataColumn
column = New DataColumn()
column.DataType = System.Type.GetType("System.Int32")
column.ColumnName = "UserID"
column.ReadOnly = False
column.Unique = True
dt.Columns.Add(column)
'add a user name column
column = New DataColumn()
column.DataType = System.Type.GetType("System.String")
column.ColumnName = "UserName"
column.ReadOnly = False
column.Unique = False
dt.Columns.Add(column)
'Add a unique column with its own unique id (for delete function)
column = New DataColumn()
column.DataType = System.Type.GetType("System.Int32")
column.ColumnName = "ID"
column.ReadOnly = False
column.Unique = True
column.AutoIncrement = True
column.AutoIncrementSeed = 1
dt.Columns.Add(column)
'add primary key (first key) on column ID
Dim PrimaryKeyColumns(0) As DataColumn
PrimaryKeyColumns(0) = dt.Columns("ID")
dt.PrimaryKey = PrimaryKeyColumns
Return dt
End Function
作者
现在我们添加一个函数来将新值添加到临时表中并将其返回给我们
VB
Private Function AddDataToTable(ByVal UserID As Int32, ByVal UserName As String, ByVal myTable As DataTable) As DataTable
Try
Dim row As DataRow
row = myTable.NewRow()
row("UserID") = UserID
row("UserName") = UserName
myTable.Rows.Add(row)
Return myTable
Catch
Return myTable
End Try
End Function
Try
Dim row As DataRow
row = myTable.NewRow()
row("UserID") = UserID
row("UserName") = UserName
myTable.Rows.Add(row)
Return myTable
Catch
Return myTable
End Try
End Function
作者
接下来,我们有一个子处理AddUser点击,这将调用上面的函数,并将临时表返回到会话并将数据重新绑定到我们的表。
VB
Protected Sub Add_Click(sender As Object, e As System.EventArgs) Handles AddUser.Click
AddDataToTable(UserAvailable.Items.FindByValue(UserAvailable.SelectedValue).Value, UserAvailable.Items.FindByValue(UserAvailable.SelectedValue).Text.ToString, CType(Session("myDatatable"),DataTable))
UserTable.DataSource = (CType(Session("myDatatable"), DataTable)).DefaultView
UserTable.DataBind()
End
AddDataToTable(UserAvailable.Items.FindByValue(UserAvailable.SelectedValue).Value, UserAvailable.Items.FindByValue(UserAvailable.SelectedValue).Text.ToString, CType(Session("myDatatable"),DataTable))
UserTable.DataSource = (CType(Session("myDatatable"), DataTable)).DefaultView
UserTable.DataBind()
End
作者
我们添加了用户删除行的功能,所以我们需要添加这个功能,它将删除所需的行并返回表。
VB
Private Function DelDataFromTable(ByVal RowID As Int32, ByVal myTable As DataTable) As DataTable
Dim r As DataRow = myTable.Rows.Find(RowID)
myTable.Rows.Remove(r)
Return myTable
End Function
Dim r As DataRow = myTable.Rows.Find(RowID)
myTable.Rows.Remove(r)
Return myTable
End Function
作者
现在我们需要一个Sub绑定到UserTable上的RowDeleting命令,该命令将调用Delete函数并重新绑定我们的数据。
VB
Protected Sub UsersForSignOffList_RowDeleting(sender As Object, e AsSystem.Web.UI.WebControls.GridViewDeleteEventArgs) Handles UserTable.RowDeleting
Dim Id As Integer = e.Keys(0).ToString
DelDataFromTable(Id, CType(Session("myDatatable"), DataTable))
UserTable.DataSource = (CType(Session("myDatatable"), DataTable)).DefaultView
UserTable.DataBind()
End Sub
Dim Id As Integer = e.Keys(0).ToString
DelDataFromTable(Id, CType(Session("myDatatable"), DataTable))
UserTable.DataSource = (CType(Session("myDatatable"), DataTable)).DefaultView
UserTable.DataBind()
End Sub
作者
因此,我们已经将功能和过程放在用户输入更新表并返回它们,所以现在我们需要从表中处理最终的输入和输出。为了做到这一点,我们要绑定一个Sub到页面的Pre-Render事件,并调用上面的一些功能,另一个将在这种情况下处理用户进入虚拟表。
VB
'Dim UserID As String 'If adding a default user
'Dim UserName As String 'If adding a default user
'Dim con As New SqlConnection({yourconnection}) 'Handle our SQL Connection here
Private Sub Page_Load() Handles Me.PreRender
If Not IsPostBack Then
GetUsers()
Dim mydt = New DataTable()
mydt = CreateTable()
Session("myDatatable") = mydt
'AddDataToTable(UserID, UserName, CType(Session("myDatatable"), DataTable)) ' If adding a default user
UsersForSignOffList.DataSource = (CType(Session("myDatatable"), DataTable)).DefaultView
UsersForSignOffList.DataBind()
End If
End Sub
Private Sub AddUsersToTable() Handles UploadTable.Click
Dim AddUser As New SqlCommand
'AddUser.Connection = con 'You will also need to open and close your connection in here
Dim dt As DataTable = CType(Session("myDatatable"), DataTable)
Dim dr As DataRow
For i = 0 To dt.Rows.Count - 1
dr = dt.Rows(i)
AddUser.CommandText = "INSERT INTO LinkedUsers(UserID) " & _
"SELECT " & dr.Item(0).ToString() & ""
AddUser.ExecuteNonQuery()
Next
End Sub
'Dim UserName As String 'If adding a default user
'Dim con As New SqlConnection({yourconnection}) 'Handle our SQL Connection here
Private Sub Page_Load() Handles Me.PreRender
If Not IsPostBack Then
GetUsers()
Dim mydt = New DataTable()
mydt = CreateTable()
Session("myDatatable") = mydt
'AddDataToTable(UserID, UserName, CType(Session("myDatatable"), DataTable)) ' If adding a default user
UsersForSignOffList.DataSource = (CType(Session("myDatatable"), DataTable)).DefaultView
UsersForSignOffList.DataBind()
End If
End Sub
Private Sub AddUsersToTable() Handles UploadTable.Click
Dim AddUser As New SqlCommand
'AddUser.Connection = con 'You will also need to open and close your connection in here
Dim dt As DataTable = CType(Session("myDatatable"), DataTable)
Dim dr As DataRow
For i = 0 To dt.Rows.Count - 1
dr = dt.Rows(i)
AddUser.CommandText = "INSERT INTO LinkedUsers(UserID) " & _
"SELECT " & dr.Item(0).ToString() & ""
AddUser.ExecuteNonQuery()
Next
End Sub
作者
上面唯一缺少的部分是将UsersAvailable下拉列表绑定到数据库(我们已经手动完成)的功能,使用虚拟SQL命令,我已经显示了下面的内容,但是该页面已被注释掉。
VB
Private Sub GetUsers()
'Dim com As New SqlCommand("SELECT * FROM Users", con)
'Dim tr = com.ExecuteReader
'UserAvailable.DataSource = tr
'UserAvailable.DataTextField = "UserName"
'UserAvailable.DataValueField = "UserID"
'UserAvailable.DataBind()
'tr.Close()
End Sub
'Dim com As New SqlCommand("SELECT * FROM Users", con)
'Dim tr = com.ExecuteReader
'UserAvailable.DataSource = tr
'UserAvailable.DataTextField = "UserName"
'UserAvailable.DataValueField = "UserID"
'UserAvailable.DataBind()
'tr.Close()
End Sub
作者
我一直发现通过简单的玩耍最容易学习,所以尝试在你的机器上,看看你可以采取多远。在这里唯一要记住的是,如果将要有大量的数据,那么绑定到数据库可能会更容易,因为这应该使您的页面的大小更小,并在服务器上使用更少的内存。