我正在制作一个网站(noob at this),我正在尝试将搜索结果添加到三个div。但是从数据库向div添加文本时会出现问题。它取得正确。但我想转换一个字符串(总共三个div,id分别为div1,div2,div3。字符串为“div”+ DivCount.ToString,DivCount为0(循环和每个循环加+1)到命令。这是代码,任何其他方法也将不胜感激。谢谢。代码如下,顺便说一句。
Default.aspx.vb
Imports Microsoft.VisualBasic
Imports System.Data.SqlServerCe
Partial Class Pages_Default
Inherits System.Web.UI.Page
'Project Variables
Dim ProjectDirectory As String = AppDomain.CurrentDomain.BaseDirectory.ToString
'ConnectAndAddItemsToDropdownList Dim
Dim SQLCommandString As String
Dim SQLConnectionString As String = "Data Source=" + ProjectDirectory + "App_Data\MainDatabase.sdf; Persist Security Info=False;"
Dim SQLConnection As New SqlCeConnection(SQLConnectionString)
Dim SQLAdapter As SqlCeDataAdapter
Dim SQLReader As SqlCeDataReader
Dim Executor As New MSScriptControl.ScriptControl
Dim DivCount As Integer = 0
Dim DivCurrent As String
Public Sub ConnectAndAddItemsToDropdownList()
DropDownList1.Items.Clear()
SQLConnection.Open()
SQLCommandString = "SELECT BookName FROM [Anthony Horowitz] WHERE (BookName LIKE '" + SearchTextBox.Text + "%')"
Dim SQLCommand As New SqlCeCommand(SQLCommandString, SQLConnection)
SQLReader = SQLCommand.ExecuteReader()
While SQLReader.Read()
DivCount = +1
DivCurrent = "div" + DivCount.ToString
Executor.Language = "VBScript"
Executor.Eval(DivCurrent.ToString + ".InnerText = SQLReader(""Bookname"")")
End While
SQLConnection.Close()
End Sub
Protected Sub SearchTextChanged(sender As Object, e As EventArgs) Handles SearchTextBox.TextChanged
ConnectAndAddItemsToDropdownList()
End Sub
End Class
Default.aspx的
<%@ Page Language="VB" CodeFile="Default.aspx.vb" Inherits="Pages_Default" AutoEventWireUp="False"%>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body id="MainPage" runat="server">
<form id="form1" runat="server">
<asp:TextBox ID="SearchTextBox" Text="Search for a book here..." runat="server" AutoPostBack="true" OnTextChanged="SearchTextChanged"></asp:TextBox>
<asp:DropDownList ID="DropDownList1" runat="server" Height="17px" Width="105px"></asp:DropDownList>
<div id="div1" runat="server">Nothing Interesting</div>
<div id="div2" runat="server">Nothing Interesting</div>
<div id="div3" runat="server">Nothing Interesting</div>
</form>
</body>
</html>
上面的结果是“需要对象:'div1'”
答案 0 :(得分:0)
您无法获取此类数据并将其放入元素中,原因有三:
将服务器控件放在您想要文本的标记中:
<div id="div1" runat="server"><asp:Label runat="server" id="label1" Text="Nothing Interesting" /></div>
获取对控件的引用并放入一个数组,以便您可以轻松访问它们:
Dim labels(2) as Label
labels(0) = label1
labels(1) = label2
labels(2) = label3
现在您可以将数据放在控件中:
While SQLReader.Read()
labels(DivCount).Text = SQLReader("Bookname")
DivCount = +1
End While