简体   繁体   中英

How to get 1 column data from DataTable and display it to Lable using VB.Net on ASP.Net

I want to get 1 column data from a DataTable that has multiple column and only 1 row record using VB.Net. And then display the column data into a web page using ASP.Net.

In my case below, I want to get the Name column data from DataTable and then display it on a web page.

Here my VB.Net Code:

 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

Here my HTML ASP.Net code:

<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>

以下是仅选择一列的代码:

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

You can use Take(1) click here to see or FirstorDefault() check it here

I will share one example rest you can check above link official document.

dt.AsEnumerable().Take(1).[Select](Function(s) s.Field(Of String)("Name"))
<asp:Label ID="lblname" runat="server" Text=""></asp:Label>

Code Behind

lblname.text=dt.Rows[0]["Name"].ToString();  VB Code 
 lblname.text=dt.Rows(0).Item("Name").ToString()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM