I'm trying to show a value from a database into a asp:label. I can show the data into a dropdownlist but not into a asp:label.
This works:
<asp:DropDownList ID="code" runat="server" DataSourceID="onlymonths"
DataTextField="itemCode" DataValueField="itemCode">
</asp:DropDownList>
I have tried to do it as follows but no luck:
<asp:Label ID="code" runat="server" DataSourceID="onlymonths"
DataTextField="itemCode" DataValueField="itemCode">
</asp:Label>
So does anyone know how to show the value into the label?
asp labels are not databound controls like dropdownlists or gridviews, you would be better off writing a method to get at the data and populating the label manually something like this
using(SqlDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
mylablel.text = rdr.GetString(0);
}
}
You need to change id of code of lable to lblCode since your drop down list id is code
Then write the following code
lblCode.Text = code.SelectedItem.Text;
Related
I have setup a hiddenfield control and a linkbutton on an aspx Masterpages content page.
<asp:HiddenField ID="HiddenField1" runat="server" value='<%# Eval("ID") %>'/>
<asp:LinkButton ID="LinkButton1" runat="server" postbackurl="orderhistorydetail.aspx">View</asp:LinkButton>
When trying to retrieve the value on the postback page using this code...
string oid = Request.Form[HiddenField1];
I am getting the error...
The name 'HiddenField1' does not exist in the current context.
Is this because of materpages? How can I fix this?
EDITED...
I viewed the source html that was generated for the page that has the hiddenfield control on it and this was the output...
<input type="hidden" name="ctl00$MainContentPlaceHolder1$ListView1$ctrl0$ctl00$HiddenField1" id="MainContentPlaceHolder1_ListView1_ctrl0_HiddenField1_0" value="12386026" />
Now, as for the code you originally gave me, I updated it to this...
HiddenField hf = Page.PreviousPage.Master.FindControl("MainContentPlaceHolder1").FindControl("ListView1").FindControl("HiddenField1") as HiddenField;
Still no luck. Am I getting close?
The page you are posting to has no knowledge of the Controls that are present on the previous page. You need to use FindControl for that.
HiddenField hf = Page.PreviousPage.Master.FindControl("ContentPlaceHolder1").FindControl("HiddenField1") as HiddenField;
string oid = hf.Value;
Or if you really want to use Request.Form you need to use the UniqueID.
string oid = Request.Form[HiddenField1.UniqueID];
First you must find the PlaceHolder of the Page that is using a Master Page and then the correct Control within the PlaceHolder.
If you want to check what all the Posted values are, use this:
foreach (string s in Request.Form.Keys)
{
Response.Write(s.ToString() + ": " + Request.Form[s] + "<br>");
}
Run through Site_materials table, any matches found store them in 'NumberOFDeliveries',
which is the ID of the label that should display them on screen.
//DELIVERIES
int NumberOfDeliveries = (from Deliveries in db.Site_Materials
where Deliveries.Diary_Entry_Id == this.DiaryEntryId
select Deliveries).ToList().Count();
if (NumberOfDeliveries > 0)
{
NoOfDeliveriesOnSite.Text = System.Convert.ToString(NumberOfDeliveries);
}
else
{
NoOfDeliveriesOnSite.Text = "0";
}
If I use the below label in my aspx page t displays as expected. But I have a problem trying to display it where i want... inside FooterTemplate/Panel/SecurePanel/Div
<FooterTemplate>
<asp:Panel runat="server" ID="AllLinks" HorizontalAlign="Center" Width="600px" >
<mesh:SecurePanel runat="server" ID="EmployeeLink" CssClass="SmallBoxLink" WebMasters="true" Admins="true" Clients="true" Employees="true">
<div style="height:25px; margin-top:12px; margin-bottom:12px;">
<asp:Label ID="Delivery" runat="server" Text="Deliveries=" /><asp:Label ID="NoOfDeliveriesOnSite" runat="server" />
As I said this code works fine and displays the correct amount(When used at diff places on the aspx page) BUT when i try to display it where I want I get the error:
from the cs. page stating 'NoOfDeliveriesOnSite' does not exist.
any ideas as to why
if it's in the footer, you will need to set the control number to -1. In this example, i have a label in the footer that I want to get a handle on:
dim myLabel as label
myLable = myDataRepeater.Controls(myDataRepeater.Controls.Count - 1).FindControl("lableName")
If there is a control you're trying to find within the user control, you may need to add a notehr .FindControl method Ie:
myLable = myDataRepeater.Controls(myDataRepeater.Controls.Count - 1).FindControl("lableName").findControls("anotherControl")
You have to find controls inside whatever container they're in.
You will want to add this above the code sample that you gave in your question, so that your reference to that variable will be valid:
SecurePanel EmployeeLink = (SecurePanel)AllLinks.FindControl("EmployeeLink");
Label NoOfDeliveriesOnSite = (Label)EmployeeLink.FindControl("NoOfDeliveriesOnSite");
Depending on what you're FooterTemplate is for (GridView, FormView, etc), you will probably need to find the "AllLinks" Panel inside that first as well.
I need to hide /unhide the labels and textbox depending on db results , I tried something like this but it doesnt works, the condition should be like if the db field is empty for that field , then the label associated with that field should hidden (not visible) , following is the code i tried :
<asp:Label ID="lblBirth" Text="DOB:" runat="server" ViewStateMode="Disabled" CssClass="lbl" />
<asp:Label ID="DOB" runat="server" CssClass="lblResult" Visible='<%# Eval("Berth") == DBNull.Value %>'></asp:Label>
Code behind:
protected void showDetails(int makeID)
{// get all the details of the selected caravan and populate the empty fields
DataTable dt = new DataTable();
DataTableReader dtr = caravans.GetCaravanDetailsByMakeID(makeID);
while (dtr.Read())
{
//spec
string value = dtr["Price"].ToString();
lblModel.Text = dtr["model"].ToString();
birthResult.Text = dtr["Berth"].ToString(); }}
To make your aspx version work your control should be data bound to data source that contains "Berth" property. As I can see from code behind, you prefer to use c# to populate controls. In this case you may just do the following:
DOB.Visible = dtr["Berth"] == DBNull.Value;
I think that using data binding is more preferable solution.
I have the following client side code in .aspx page within a datalist itemtemplate that takes questions from the database like this:
<Itemtemplate>
<b> <%=GetQuestionNum()%>)
<%#Server.HtmlEncode(Eval("Text").ToString())%></b>
<br />
<asp:Panel ID="A" runat="server" Visible='<%#GetVisible(Eval("OptionA").Tostring())%>'>
<input name="Q<%#Eval("ID")%>" type="radio" value="A">
<%#Server.HtmlEncode(Eval("OptionA").ToString())%>
</option><br />
</asp:Panel>
<asp:Panel ID="B" runat="server" Visible='<%#GetVisible(Eval("OptionB").Tostring())%>'>
<input name="Q<%#Eval("ID")%>" type="radio" value="B">
<%#Server.HtmlEncode(Eval("OptionB").ToString())%>
</option><br />
</asp:Panel>
<asp:Panel ID="C" runat="server" Visible='<%#GetVisible(Eval("OptionC").Tostring())%>'>
<input name="Q<%#Eval("ID")%>" type="radio" value="C">
<%#Server.HtmlEncode(Eval("OptionC").ToString())%>
</option><br />
</asp:Panel>
<asp:Panel ID="D" runat="server" Visible='<%#GetVisible(Eval("OptionD").Tostring())%>'>
<input name="Q<%#Eval("ID")%>" type="radio" value="D">
<%#Server.HtmlEncode(Eval("OptionD").ToString())%>
</option><br />
</asp:Panel></itemtemplate>
The output is like:
1) What is your age group?
- Option 1
- Option 2
- Option 3
- Option 4
The ID's of the radio buttons are dynamic ("Q" & QuestionID). If there is no answer to a question then the GetVisible function returns false and the containing panel is hidden.
I have been trying to get rid of the html and replace these with asp:radiobuttons but it is not possible to set id's from databinding.. only simply. I was trying something like:
<asp:RadioButton ID="Q<%#Eval("ID")%>" runat="server" Visible='<%#GetVisible(Eval("OptionA").Tostring())%>'
Text='<%#Server.HtmlEncode(Eval("OptionA").ToString())%>' />
Here is the function that provides data:
Public Shared Function GetQuestionsForSurvey(ByVal id As Integer) As DataSet
Dim dsQuestions As DataSet = New DataSet()
Try
Using mConnection As New SqlConnection(Config.ConnectionString)
Dim mCommand As SqlCommand = New SqlCommand("sprocQuestionSelectList", mConnection)
mCommand.CommandType = CommandType.StoredProcedure
Dim myDataAdapter As SqlDataAdapter = New SqlDataAdapter()
myDataAdapter.SelectCommand = mCommand
mCommand.CommandType = CommandType.StoredProcedure
mCommand.Parameters.AddWithValue("#id", id)
myDataAdapter.Fill(dsQuestions)
mConnection.Close()
Return dsQuestions
End Using
Catch ex As Exception
Throw
End Try
End Function
but I'm finding it impossible to work with the html controls, i.e get their .text value from codebehind, or adding events!
Please can an expert suggest a better way to replace the html with suitable asp.net web controls or from the codebehind and output it. Or point me in the right direction?
Thanks :0)
I had some experience with ASP controls and data binding. The problem you are facing is probably the fact that once you declare a control via markup you can't access it from data binding. Also, you should not confuse the server-side ID with the client-side ID.
The server-side ID, mapped to Id property of controls, is used to programmatically access the control from code behind. Client-side ID is the ID that will be placed in tag's id attribute and is mapped to ClientId property.
Judging from your question, what you need is to build a multi-choice survey, and, in my opinion, it's not important how the IDs are generated, just that they are properly grouped for each question.
I'll answer the part of programmatically accessing controls in data binding, which is a part of your question.
Here is an example from my code. Suppose you have a very simple GridView like this
<asp:GridView ID="example" runat="server" OnRowDataBound="DataBound">
<Columns>
<asp:TemplateField HeaderText="New">
<ItemTemplate>
<asp:Image ID="imgExample" runat="server" />
</ItemTemplate>
</Columns>
</asp:GridView>
It takes a data set during data binding and sets the image according to some property. It works the same as DataList, don't worry.
Now, in code behind, you handle the RowDataBoundEvent. You can't access the imgExample object directly, because it's a child of the ItemTemplate. When the row is bound, you have direct access to the row and then you can use the FindControl method of Control class
Here is C# code example (easy to convert to VB)
protected void DataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow) //Required
{
GridViewRow row = e.Row;
[...] //get an email message
(row.Cells[0].FindControl("imgExample") as Image).ImageUrl = (email.AlreadyRead)
? "Mail_Small.png"
: "Mail_New_Small.png";
}
}
Application to your case
In order to build a multi-choice survey, my advice is to create a DataList that will hold questions (the outer control) and then, for each row, declare a RadioButtonList that holds answers (the inner control). Bind the outer data list to the data set of questions and answers. Handle the RowDataBound event or whatever it's called in the DataList world. When you handle that event, bind the inner radiobuttonlist to the answers.
It should work for you
I am actually working on something similar at the moment. I am using javascript and jQuery to dynamically add controls to my page. After adding them to my page I have to get the new controls, their text, etc. The way I've been doing it is something like this:
<table id='BuilderTable' class="BuilderTable">
<tbody class='BuilderBody'>
</tbody>
</table>
<asp:Button runat="server" ID="saveButton" OnClick="SaveButton_Click" OnClientClick="SaveData()"
Text="Save Form" />
<asp:HiddenField runat="server" ID="controlsData" />
This table is where I put all my new controls.
Then when the client clicks the save button it first calls this javascript / jQuery function:
function SaveData() {
var controlRows = $('#BuilderTable tr.control');
var controls= [];
controlRows.each(function (index) {
//process control information here ...
controlText = //use jQuery to get text, etc...
var control = {
Index: (index + 1),
Text: controlText
};
controls.push(control);
});
var str = JSON.stringify(questions);
$('#<%= controlsData.ClientID %>').val(str);
}
Then the server side function for the button click is called (this in in C#, adapt to VB).
protected void SaveButton_Click(object sender, EventArgs e)
{
JavaScriptSerializer jss = new JavaScriptSerializer();
string str = controlsData.Value;
List<Control> controls = jss.Deserialize<List<Control>>(str);
}
Using a Control class like this:
public class Control
{
public int Index { get; set; }
public string Text { get; set; }
}
This code uses javascript and jQuery to get your controls, JSON to serialize the data and save it in a asp hiddenfield then grab the data server-side and deserialize into objects that your code can use. Then take the data and do whatever you need to.
When creating a Gridview at design time you can create a template column like this:
<asp:TemplateField>
<ItemTemplate>
<asp:Label runat="server" ID="Label1"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
And in the HTML it will give it a unique name like:
<span id="gvSelect_ctl02_Label1">blahblah</span>
And I can then reference this label in the code behind by:
CType(e.Row.FindControl("Label1"), Label)
Which is PERFECT. But I can't figure out how to do this when I'm creating TemplateFields Dynamically. I've got the following code in my "InstantiateIn":
Dim hl As New HiddenField
hl.ID = "hHidden"
hl.Value = 0
AddHandler hl.DataBinding, AddressOf Me.hl_DataBinding
container.Controls.Add(hl)
And this DOES create a hidden control with the ID as hHidden in each row. But it doesn't give it the unique ID like "gvSelect_ctl02_hHidden" it's just "hHidden". And I know there are ways to append the row number to it myself. But I was wondering if there was a way for it to do this automatically. And still allowing me to reference the hiddenfield like:
CType(e.Row.FindControl("hHidden"), HiddenField)
Ugh.. another answer to my own question. I was looking for the name in the RowCreated. I should have been looking for it in the RowDataBound event.
it works now.. now that I'm doing it correctly.
(I may have too many things on the go at once..) :S