Saturday, March 31, 2012

Setting label text from database from code behind

I have this function in my code behind file...


Function GetPageTitle() As System.Data.DataSet
Dim connectionString As String = "server=xxx; user id=xxx; password=xx; database=xx"
Dim dbConnection As System.Data.IDbConnection = New System.Data.SqlClient.SqlConnection(connectionString)
Dim CurrentPageName As String = Request.Params("pagename")
'create the connection object
'Dim connection As New SqlConnection(connectionString)

Dim queryString As String = "SELECT [Content].[PageTitle] FROM [Content] WHERE ([Content].[Page" & _
"Name] = @dotnet.itags.org.CurrentPageName)"
Dim dbCommand As System.Data.IDbCommand = New System.Data.SqlClient.SqlCommand
dbCommand.CommandText = queryString
dbCommand.Connection = dbConnection

Dim dbParam_pagename As System.Data.IDataParameter = New System.Data.SqlClient.SqlParameter
dbParam_pagename.ParameterName = "@dotnet.itags.org.CurrentPageName"
dbParam_pagename.Value = CurrentPageName
dbParam_pagename.DbType = System.Data.DbType.String
dbCommand.Parameters.Add(dbParam_pagename)

Dim dataAdapter As System.Data.IDbDataAdapter = New System.Data.SqlClient.SqlDataAdapter
dataAdapter.SelectCommand = dbCommand
Dim dataSet As System.Data.DataSet = New System.Data.DataSet
dataAdapter.Fill(dataSet)

Return dataSet
End Function

and I would like it to return a text value to set the text of this label


<asp:label id="PageTitleLabel" runat="server" Text="<%# GetPageTitle () %>"></asp:label>

I also call page.databind in page load.

The result I get when I run the page is "System.Data.DataSet" as the label text!!!

I can find plenty of books and articles databinding grids, lists and repeaters but all I want is a humble label.

Thanks

SimonOK, you are assigning a whole dataset to a text field, so it will simply get the Object name which is "System.Data.DataSet" Try this, instead of having the function return a dataset "As System.Data.DataSet" return a string "As String". Now when you populate the DataSet inside your function (I don't know how many records you will get on the DataSet) find the record in the DataSet and return is as a string like:

This is C#


Return dataSet["page_title"].ToString();

Now you have the page title returned instead of the entire dataset.

Good Luck
Thanks for the response.

I got me on the right road.

Simon

0 comments:

Post a Comment