Displaying data from DataReader in Label control (ASP.NET) - asp.net

I have a query that returns one row so I want to display it in the Label, but I can't find the property DataSource on it.
How can I do this ?

If you're using a SqlDataReader in C# then you want something like this
string label;
if (reader.Read())
{
label = reader.IsDBNull(reader.GetOrdinal("Column"))
? String.Empty
: reader.GetString(reader.GetOrdinal("Column"));
}
reader.Close();
MyLabel.Text = label;
In VisualBasic.Net it will be something like
Dim label as String
If reader.HasRows Then
Label = reader.GetString(reader.GetOrdinal("ColumnName"))
End If
reader.Close
MyLabel.Text = label

If you are only returning one row with one column you might want to use command.ExecuteScalar() instead of a data reader. Then you can just set your label like this:
lblAnswer.Text = myCommand.ExecuteScalar().ToString()

I know this is a bit old thread, but the above did not work for me. But this did:
If reader.HasRows Then
label = reader("columnName")
labelName.Text = label
End If
smc

Related

Get value of BLOB field and show/hide a label based on it

I'm calling some data from my Oracle table and I have a field which is called 'image1' which is a BLOB field.
Sometimes an image is input into the field and others it's not. I need a way to read the BLOB field to see if its a blank and then show/hide my label based on its contents.
Here's my source code
query = OracleConn.CreateCommand()
query.CommandText = "select * from articles"
DataTable = New DataTable()
OracleDataAdapter = New OracleDataAdapter(query)
OracleDataAdapter.Fill(DataTable)
GridView1.DataSource = DataTable.DefaultView
GridView1.DataBind()
If DataTable.Rows(0).Item("image1") = "" Or DataTable.Rows(0).Item("image1") Is Nothing Then
lbl1.Visible = False
End If
This doesn't seem to do what it's suppose to do.
Any ideas how i can accomplish my goal?
Thanks
You should test to see if image1 is DBNull:
If DataTable.Rows(0).Item("image1") Is DBNull.Value Then

Loop through the labels of a page to assign text

I have some 20 labels on my aspx page for which the IDs are lbl1,lbl2....lbl20 and text is driven by SqlServer table. Is there any easy way to loop through all the labels on the page and assing the text from reader.
I did some thing like but it doesn't work.
SqlDataReader Reader = new SqlDataReader();
int i = 0;
while(Reader.read())
{
label lbl = new label();
lbl.ID = "label" + i;
lbl.text = Reader["ColumnName"].ToString();
}
Is there any other method through which I can loop through all the labels and assign text for it?
If you have them in a container, i think you can do something like this below:
For Each lbl As Control In Grid1.Children
If TypeOf lbl Is Label Then
'your logic
End If
Next
I have only tried this in silverlight however, so i'm not sure it works, or if putting them all in a container is practical in your case.
One way to do this is use the findcontrol method. This would work well because all your labels are named with a "lbl0", "lbl1"... convention.
**start looping:
int index = 0;
string currentLabel = "lbl" + index.ToString();
index++;
Control myControl1 = FindControl(currentLabel);
// cast control to type: (label)
// apply text from reader**
Give that a shot. Hope it works out
I have used this in the past and I just tested it out.
You can do this because every page has a form
HtmlForm form1 = (HtmlForm)Page.FindControl("ContentPlaceHolder1");
for (int i = 1; i <= 3; i++) {
((TextBox)form1.FindControl("label" + i)).Text = "This is label number " + i;
}
If you have a master page change the first line to this
ContentPlaceHolder ph = (ContentPlaceHolder)Page.FindControl("ContentPlaceHolder1");

SqlDataSource.Select()? How do I use this? (ASP.net)

I'm trying to retrieve values using VB.NET from a SQL database. How do I use SqlDataSource.Select()? Is there a way to move the value to a variable that I can use for other things?
I know its kind of scattered and vague but that is the best I can do. I basically need to set a labels text to a value in a table.
This puts the result query in to a DataTable.
DataView view = (DataView)dataSource.Select(new DataSourceSelectArguments());
DataTable groupsTable = view.ToTable();
String value;
foreach (DataRow dr in dt.Rows)
{
// Do something here IE grab the value of the first column
value = dr[0];
}
Repying to last question in comment:
YourTable.Rows(index)(index)
YourTable.Rows(index)("columnname")
I was getting crazy trying to do this simple operation:
retrieving data from sqldatasource and put it into variables that I can manipulate.
At the end, Here the working behind code to do this for VB.NET:
Dim DV As New DataView()
Dim DataTable As New DataTable()
Dim SqlDataSource1 As New SqlDataSource()
Dim VALUE As String
SqlDataSource1.ID = "SqlDataSource1"
Me.Page.Controls.Add(SqlDataSource1)
SqlDataSource1.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings("Connection_name").ConnectionString
SqlDataSource1.SelectCommand = "SELECT * from Table"
DV = CType(SqlDataSource1.Select(DataSourceSelectArguments.Empty), DataView)
DataTable = DV.ToTable()
For Each riga As DataRow In DataTable.Rows
VALUE = riga("table_name").ToString
Next
the for each, in this case gets only the first value but you can get any value from datatable and put it into vector, or other strings, so you can control data coming from sqldatasource.
ENJOY

Programatically created ASP.NET TextBox retains Text value after PostBack even if Control is cleared

I have a drop down menu, and based on which item is selected, I call a web service and then dynamically create some text boxes.
The first time I drop down the menu and select an item, it works perfectly, and the text boxes are created and populated dynamically. However, the next time I drop down the menu (after the first postback), and select something different... after the second postback, the original values remain in the textboxes.
I am clearing all of the text boxes out of the placeholder, then re-creating them, and then setting a NEW value, how can they retain the OLD values... especially if I controls.clear them from the page?
Note: The second time they are being created, the textbox IDs DO end up being the same. Could that have something to do with it? This duplicate ID functionality will need to be supported.
My code, called from Page_Load, is as follows: (edited to add more code)
Private Sub RefreshEntity()
Dim XmlRecords As New XmlDocument
Dim XmlRecordsNode As XmlNode
Dim EntityType As String = EntityTypes.SelectedValue
Dim Entity As String = RecordValue.Value
Dim FieldName As String
Dim FieldValue As String
FieldPlaceHolder.Controls.Clear()
If RecordList.SelectedValue <> "Select..." Then
Try
XmlRecordsNode = LoginInfo.SharePointConnectWebService.GetMetaData(LoginInfo.WSUser, LoginInfo.WSPass, _
EntityType, Entity)
XmlRecords.LoadXml(XmlRecordsNode.OuterXml)
Catch ex As Exception
ConfirmLabel.Text = "<b>Error:</b><br>" & ex.Message.ToString
Return
End Try
Else
SetProperties.Visible = False
Return
End If
For Each OneNode As XmlNode In XmlRecords.SelectNodes("Fields").Item(0).ChildNodes
FieldName = OneNode.Name
FieldValue = OneNode.InnerText
Dim newLabel As Label = New Label()
newLabel.Text = FieldName & ": "
Dim newTextBox As TextBox = New TextBox()
newTextBox.ID = "Field-" & FieldName
newTextBox.Text = FieldValue
Dim newLine As Label = New Label()
newLine.Text = "<br><br>"
FieldPlaceHolder.Controls.Add(newLabel)
FieldPlaceHolder.Controls.Add(newTextBox)
FieldPlaceHolder.Controls.Add(newLine)
Next
SetProperties.Visible = True
End Sub
And the RecordValue.Value is a hidden field that gets populated in every Page_Load:
RecordValue.Value = RecordList.SelectedValue
Where RecordList is my DropDown menu.
This is likely due to ViewState or the Posted values clobbering your values.
Once a control is dynamically added to the controls collection it needs to catch up with all the page life cycle events that have already fired. In the case of a post back this means that the ViewState and/or the posted form value will clobber the .text property on the TextBox based on the order you're adding the dynamic controls to the controls collection and setting the .text property.
To fix this you can disable ViewState by setting the .EnableViewState property to false on the dynamically generate controls also add the controls to the controls collection before you set any properties on them.
For Each OneNode As XmlNode In XmlRecords.SelectNodes("Fields").Item(0).ChildNodes
FieldName = OneNode.Name
FieldValue = OneNode.InnerText
Dim newLabel As Label = New Label()
Dim newTextBox As TextBox = New TextBox()
Dim newLine As Label = New Label()
newTextBox.ID = "Field-" & FieldName
newLabel.EnableViewState = False
newTextBox.EnableViewState = False
newLine.EnableViewState = False
FieldPlaceHolder.Controls.Add(newLabel)
FieldPlaceHolder.Controls.Add(newTextBox)
FieldPlaceHolder.Controls.Add(newLine)
newLabel.Text = FieldName & ": "
newTextBox.Text = FieldValue
newLine.Text = "<br><br>"
Next
You're not storing the value in a Session variable and then putting it back into the text box later in your code?

Compare values from data source to string

I'm just stumped on what to do with this code, I'm just trying to implement a 'no duplicates' catch on my insert customer form, but it just slips through my if statement to the else everytime. This is the source. Also I tried a .Equals with the same results :(
Protected Sub srcAllClients_Inserting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.SqlDataSourceCommandEventArgs) Handles srcAllClients.Inserting
'Establish Variables
Dim emailAddress As String
Dim srcUsers As SqlDataSource = New SqlDataSource()
srcUsers.ConnectionString = ConfigurationManager.ConnectionStrings("ISSD21ConnectionString").ConnectionString
Dim view As DataView
view = DirectCast(srcUsers.Select(DataSourceSelectArguments.Empty), DataView)
srcUsers.SelectCommand = "SELECT EmailAddress FROM ISSDClients"
srcUsers.DataSourceMode = SqlDataSourceMode.DataReader
Dim reader As IDataReader
reader = DirectCast(srcUsers.Select(DataSourceSelectArguments.Empty), IDataReader)
emailAddress = FormView1.FindControl("txtEmail").ToString
While reader.Read()
If reader("EmailAddress") = (emailAddress) Then
lblError.Text = "Your Email is NOT Unique!"
'this is where we cancel the update and return an error
Else
lblError.Text = "Your Email is Unique!"
'nothing needs to happen, maybe just tell them that it went through
End If
End While
reader.Close()
End Sub
emailAddress = FormView1.FindControl("txtEmail").ToString
is just going to return the string "System.Web.UI.WebControls.TextBox". You're not accessing the actual property of the control that would hold the text value, you're just calling ToString() on the control itself.
Try this:
Dim emailBox As TextBox = CType(FormView1.FindControl("txtEmail"), TextBox);
emailAddress = emailBox.Text
In addition to Womp's answer...
In the while loop that is running through the email records, you need to break out of the loop once you find a matching email and alert the user.
if reader("EmailAddress") = (emailAddress) then
'1. Break from the Loop
End if
I would recommend that you pass the emailAddress to the SQL Server as a parameter.
Select Count(EmailAddress) From ISSDClients
Where EmailAddress = #EmailAddress
Execute this statement using ExecuteScalar and cast the result as an integer. If the result is zero then you are ok, otherwise display an error.
Doing it this way avoids using the while loop and should be much quicker if your table has lots of rows.
You also need to get the Text property from the Email Text box.
emailAddress = FormView1.FindControl("txtEmail").Text.ToString
You may want to take a look at the String.Compare method, which will make it easier to compare without respect to things like case sensitivity and culture. It does consider whitespace to be part of your string, so you may wish to trim the string prior to calling it, to help normalize.
For example, the following strings would be considered equal:
var firstString = "some StrinG to Compare ";
var secondString = " somE string to COMPARE";
var equal = (String.Compare(firstString.Trim(), secondString.Trim(), StringComparison.InvariantCultureIgnoreCase) == 0);

Resources