【发布时间】:2013-09-17 07:39:31
【问题描述】:
我有一个由dataTable 填充的Gridview,由DataAdapter 填充。这就是最初在Page_Load 中加载网格的方式。
为了添加搜索功能,我做同样的事情,但将TextBox.Text 作为参数传递给SELECT... LIKE ... 语句。
要添加编辑功能(每行中的一个按钮),我需要 dataTable 中的先前数据,如果我在编辑之前执行搜索,我只需要 dataTable 中的搜索结果。
问题是,我不知道如何保持它的价值(持久),当我按下编辑按钮时,dataTable 有 0 列,所以它不显示任何要编辑的内容。
我想这是因为我正在使用Using,而dataTable 可能在End Using 之后被清理。
在这种情况下,我能做些什么来解决它?本来想把miconn.Close()去掉,但是什么都解决不了,其实我不知道End Using之后连接是否还在。
代码:
Dim con As New Connection
Dim table As New DataTable()
Private Sub fill_grid()
Using miconn As New SqlConnection(con.GetConnectionString())
Dim sql As String = "SELECT area,lider_usuario FROM AREA"
Using command As New SqlCommand(sql, miconn)
Using ad As New SqlDataAdapter(command)
ad.Fill(table)
GridView1.DataSource = table
GridView1.DataBind()
'miconn.Close()
End Using
End Using
End Using
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
fill_grid()
End If
End Sub
Protected Sub btnSearch_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSearch.Click
Dim miCon As New Connection
Using miconn As New SqlConnection(miCon.GetConnectionString())
Dim sql As String = "SELECT area,lider_usuario FROM AREA WHERE area LIKE @area"
Using command As New SqlCommand(sql, miconn)
command.Parameters.Clear()
command.Parameters.Add("@area", SqlDbType.VarChar).Value = "%" + TextBox1.Text + "%"
Using ad As New SqlDataAdapter(command)
ad.Fill(table)
GridView1.DataSource = table
GridView1.DataBind()
'miconn.Close()
End Using
End Using
End Using
End Sub
Protected Sub EditRow(ByVal sender As Object, ByVal e As GridViewEditEventArgs)
GridView1.EditIndex = e.NewEditIndex
GridView1.DataSource = table
GridView1.DataBind()
End Sub
Protected Sub CancelEditRow(ByVal sender As Object, ByVal e As GridViewCancelEditEventArgs)
GridView1.EditIndex = -1
GridView1.DataSource = table
GridView1.DataBind()
End Sub
【问题讨论】:
-
为什么不使用缓存、服务器端或客户端?即视图状态、会话、缓存
-
在谷歌搜索时,我告诉你我不知道那是什么。能举个例子吗?
-
在下面查看我的答案,使用视图状态
标签: asp.net vb.net gridview ado.net datatable