1

我想使用 VB.Net 从具有多列且只有 1 行记录的 DataTable 中获取 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>
4

3 回答 3

2

这是只选择一列的代码:

dt.Rows.Item(0).Item("Name")

于 2019-04-10T04:59:28.647 回答
0

您可以使用 Take(1) click here to see或 FirstorDefault() check it here

我将分享一个示例,您可以查看上面的链接官方文档。

dt.AsEnumerable().Take(1).[Select](Function(s) s.Field(Of String)("Name"))
于 2019-04-10T04:33:00.747 回答
0
<asp:Label ID="lblname" runat="server" Text=""></asp:Label>

代码背后

lblname.text=dt.Rows[0]["Name"].ToString();  VB Code 
 lblname.text=dt.Rows(0).Item("Name").ToString()
于 2019-04-10T06:01:02.743 回答