开发者

set label value in vb.net

开发者 https://www.devze.com 2023-01-02 11:40 出处:网络
I\'m usually a PHP guy but got stuck doing a project in vb.net. I have a query (sqldatasource) that returns a single value (the last update date).

I'm usually a PHP guy but got stuck doing a project in vb.net.

I have a query (sqldatasource) that returns a single value (the last update date).

I want to use a label to say something like "Last updated: " < Label = (returned value) >

In PHP this would be simple. In vb.net, all I can find are endless badly written code behinds showing how you'd execute the qu开发者_开发知识库ery onLoad then bind it to the label.

Is this really the only way to do this? It seems like a ridiculously simple problem to have such a long solution. I have used a datagrid control to just bind the query result directly, but it prints the column name as well as the date, so it's not ideal.

Any ideas?


In your Page_Load method, run your query. On your page.aspx, you have a form control, lets call it label1. Set label1.text = queryResult.

Sub Page_Load()
  dim myConnection as new data.sqlclient.sqlconnection
  dim myCommand as new data.sqlclient.sqlcommand
  dim sqlReader as data.sqlclient.sqldatareader
  myConnection.connectionString = 'enter your connection string details'
  myConnection.Open()
  myCommand = New SqlCommand("Select lastUpdated from yourTable", myConnection)
  sqlReader = myCommand.ExecuteReader()
  if sqlReader.hasRows then
    sqlReader.read()
    label1.text = Format("MM/dd/yyyy", sqlReader("lastUpdated"))
  end if
End Sub

And your page.aspx (somewhere)

<asp:label id="Label1" runat="server" />

PS - I may be off on the format function above, been awhile.

EDIT based on user comment:

Well, for what you are doing, I wouldn't really recommend a SQLDataSource as it is really meant to be bound to a control such as a gridview or repeater. However, if you want to use the SQLDataSource, you will need to bind to a DataView in your code-behind. From there, you can access each row (you should only have one) and column by name.

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    Dim dv As New Data.DataView
    'use the id of your SqlDataSource below'
    dv = SqlDataSource1.Select(DataSourceSelectArguments.Empty)
    Label1.Text = dv.Table.Rows(0)("LastUpdated")
End Sub

TO use a connection string from the web.config:

Web.Config File:

<appSettings>  
   <add key="strConnectionString" value="Data Source=192.168.0.55;Database=Times;User ID=sa;PassWord=sa"/> 
</appSettings>

Code Behind:

     Dim sqlConn as new data.sqlClient.SqlConnection()
     sqlConn.ConnectionString=ConfigurationManager.ConnectionStrings("strConnectionString").ConnectionString
     sqlConn.Open()
0

精彩评论

暂无评论...
验证码 换一张
取 消