我想使用VB.Net从具有多列且只有1行记录的数据表中获取1列数据。然后使用ASP.Net将列数据显示到网页中。
在下面的例子中,我想从DataTable中获取Name列数据,然后将其显示在网页上。
这是我的VB.Net代码:
Imports System
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Public Class TestDisplayData
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
'Create a Connection Object
Dim connectionString As String
Dim connection As SqlConnection
connectionString = ConfigurationManager.ConnectionStrings("SQLDbConnection").ToString
connection = New SqlConnection(connectionString)
'Create SQL Command
Dim SQL As String = "SELECT Name, Title, Phone FROM contacts"
'Open the Connection
connection.Open()
'Create DataAdaptor Object
Dim Adaptor As SqlDataAdapter = New SqlDataAdapter()
Adaptor.SelectCommand = New SqlCommand(SQL, connection)
'Close the Connection
connection.Close()
'Create DataTable Object
Dim dt As DataTable = New DataTable()
'Fill DataTable
Adaptor.Fill(dt)
'I am not sure what next code are. I want to get the Name column from the DataTable
End Sub
End Class
这是我的HTML ASP.Net代码:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
Name: (I want to display the Name column data here)
</div>
</form>
</body>
</html>
答案 0 :(得分:2)
这里是仅选择一列的代码:
dt.Rows.Item(0).Item("Name")
答案 1 :(得分:0)
您可以使用Take(1)click here to see或FirstorDefault()check it here
我将分享一个示例,您可以查看上面的链接官方文件。
dt.AsEnumerable().Take(1).[Select](Function(s) s.Field(Of String)("Name"))
答案 2 :(得分:0)
lblname.text=dt.Rows[0]["Name"].ToString(); VB Code
lblname.text=dt.Rows(0).Item("Name").ToString()
隐藏代码
{{1}}