我有一些使用while循环创建的按钮存储在占位符中,占位符在创建时的CommandArguments等于数据库中单个列的唯一字段。
单击时,按钮的单击过程使用按钮的CommandArgument从数据库中检索数据,以确定要显示的数据。
我的问题是当页面加载时,我希望默认选择第一个按钮并触发其onClick事件。有没有办法在If Not Page.IsPostBack
内执行此操作,还是必须使用JavaScript / jQuery?
到目前为止,这是我的代码:
<!DOCTYPE HTML>
<%@ Page Language="VB" Debug="true" ClientTarget="uplevel" %>
<%@ import Namespace="System.Data.OleDb" %>
<%@ import Namespace="System.Data" %>
<script runat="server">
Dim dbConnection As OleDbConnection
Dim dbCommand As OleDbCommand
Dim dbReader As OleDbDataReader
Dim sqlString As String
Sub Page_Load()
Try
dbConnection = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;data source=" & Server.MapPath("MyDatabase.accdb"))
dbConnection.Open()
sqlString = "SELECT DISTINCT Type FROM MyTable"
dbCommand = New OleDbCommand(sqlString, dbConnection)
dbReader = dbCommand.ExecuteReader()
While dbReader.Read()
Dim myButton As Button = New Button()
myButton.ID = dbReader("Column2")
myButton.Text = dbReader("Column2")
myButton.CommandArgument = dbReader("Column2")
myButton.EnableViewState = False
AddHandler myButton.Command, AddressOf myClickSub
myPlaceholder.Controls.Add(myButton)
End While
dbReader.Close()
Finally
dbConnection.Close()
End Try
End Sub
Sub myClickSub(src As Object, args As CommandEventArgs)
Try
dbConnection.Open()
sqlString = "SELECT * FROM MyTable WHERE Column2 = '" & args.CommandArgument & "'"
dbCommand.CommandText = sqlString
dbReader = dbCommand.ExecuteReader()
myRepeater.DataSource = dbReader
myRepeater.DataBind()
dbReader.Close()
Finally
dbConnection.Close()
End Try
End Sub
</script>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>My Page</title>
</head>
<body>
<form runat="Server">
<div>
<asp:PlaceHolder ID="myPlaceholder" runat="server" />
<br />
<asp:Repeater id="myRepeater" runat="server">
<HeaderTemplate>
<table>
<tr>
<th scope="col">ID</th>
<th scope="col">Foo</th>
<th scope="col">Bar</th>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td><%# Eval("Column1")%></td>
<td><%# Eval("Column3")%></td>
<td><%# Eval("Column4")%></td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
</div>
</form>
</body>
</html>
答案 0 :(得分:1)
我希望默认选择第一个按钮
技术上您希望默认情况下第一条记录显示。单击按钮是一个单独的问题。所以将它分成它自己的功能:
Sub BindRepeater(ByVal column2 as String)
Try
dbConnection.Open()
sqlString = "SELECT * FROM MyTable WHERE Column2 = '" & column2 & "'"
dbCommand.CommandText = sqlString
dbReader = dbCommand.ExecuteReader()
myRepeater.DataSource = dbReader
myRepeater.DataBind()
dbReader.Close()
Finally
dbConnection.Close()
End Try
End Sub
然后在点击处理程序中:
Sub myClickSub(src As Object, args As CommandEventArgs)
BindRepeater(args.CommandArgument)
End Sub
现在您可以从Page_Load
调用相同的函数:
If Not Page.IsPostBack
BindRepeater(someValue)
End If
(你得到的地方someValue
取决于你。我想它是来自数据源中第一条记录的东西吗?)
此外, 这很重要 ,您的数据访问代码对SQL注入攻击持开放态度。您真的确实想要使用参数化查询。
答案 1 :(得分:0)
嘿,在Page.IsPostBack
事件
btnSwitchToType1_Click(this, null);
希望有所帮助