从DataTable读取数据 - ASP.NET

时间:2015-06-26 06:11:50

标签: c# asp.net vb.net datatable

我在VB.net上使用ASP.net 4.5。 (C#示例也可以,我会转换它)

我使用以下代码填充表单上的Repeater Control。

Private pgdArticles As New PagedDataSource

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        pgdArticles = GetData()
        blogRepeater.DataSource = pgdArticles
        blogRepeater.DataBind()

    End Sub


    Private Function GetData() As PagedDataSource

        Dim pg As New PagedDataSource

        Dim conn As SqlConnection
        conn = New Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings("myConnectionString").ConnectionString)

        Dim cmd As New SqlCommand("usp_MyProc", conn)

        Dim da As New SqlDataAdapter()
        da.SelectCommand = cmd
        Dim dt As New Data.DataTable()
        da.Fill(dt)
        pg.DataSource = dt.DefaultView

        Return pg

    End Function

它适用于使用转发器但我想读取该数据并在我的表单上填充标签而不使用转发器。像下面的东西....

我的数据在我的表格中.................

My data in my table

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        pgdArticles = GetData()

        If pgdArticles.ID = 1 Then
            lblName1 = pgdArticles.Name 'This will be value Mike
            lblValue1 = pgdArticles.Value 'This will be value 250
        End If

        If pgdArticles.ID = 2 Then
            lblName2 = pgdArticles.Name 'This will be value Ben
            lblValue2 = pgdArticles.Value 'This will be value 400
        End If

    End Sub

那么还有其他办法吗? C#或VB.NET代码示例没问题。

1 个答案:

答案 0 :(得分:1)

代码:

Public Property dtArticles As DataTable

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load

    dtArticles = GetData()

    For I As Integer = 0 To dtArticles.Rows.Count - 1
        Dim row As DataRow = dtArticles.Rows(I)
        Dim label As Label = Page.FindControl(String.Format("Name{0}", I))
        label.Text = String.Format("{0} ({1})", row("Name"), row("Value"))
    Next

End Sub

Private Function GetData() As DataTable

    Dim conn As New Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings("myConnectionString").ConnectionString)
    Dim cmd As New SqlCommand("usp_MyProc", conn)

    Dim da As New SqlDataAdapter()
    da.SelectCommand = cmd

    Dim dt As New Data.DataTable()
    da.Fill(dt)

    Return dt

End Function

HTML:

<asp:Label ID="Name0" runat="server" />
<asp:Label ID="Name1" runat="server" />
<asp:Label ID="Name2" runat="server" />