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.
Related
I have an asp:GridView containing a CommandField.
When I click on the delete image, OnRowDeleting will be called in the code behind.
I want to add a confirm dialog, using jquery.
Trying this:
$('input[alt="Ta bort"]').click(function(e)
{
var target = e.which;
var tr = $(target).closest('tr');
var td = tr.find("td:first");
if (!confirm("Do you want to remove the line where the first cell reads" + td.text() + "?"))
{
return false;
}
});
I have no idea how the text "Ta bort" actually comes into that alt attribute, its "remove" in my language, must be automatically generated, because nothing in my aspx code reads "Ta bort". I find no other way of writing a selector easily beside using that alt text.
The confirm appears, but the event will never get cancelled. Meaning that even if I choose "no", the line is removed.
Why?
I also tried e.preventDefault();
I do not want to create a TemplateField instead of CommandField as suggested at Delete Confirmation Message in CommandField?
you can use like below
<asp:LinkButton ID="lnkDelete" runat="server" CausesValidation="False"
CommandName="Delete" Text="Delete" OnClientClick="return confirm('Are you sure you want to delete this record');"></asp:LinkButton>
refer this reference link
I have a dynamically named DIV in a GridView which contains a user control with a dynamically assigned Parent_ID. The javascript is used to show or hide the DIV. I'll show you two examples of different rows without the ASP code.
Row 1 showing for Order # 123456:
<a href="<%#"javascript:collapseExpand('Order_Notes_Panel123456');" %>" >+</a>
<div id='Order_Notes_Panel123456' style="display:none;">
<uc:Comments_Control id="Comments_Control_ID" runat="server" Parent_ID='123456'/>
</div>
Row 2 showing for Order # 678901:
<a href="<%#"javascript:collapseExpand('Order_Notes_Panel678901');" %>" >+</a>
<div id='Order_Notes_Panel678901' style="display:none;">
<uc:Comments_Control id="Comments_Control_ID" runat="server" Parent_ID='678901'/>
</div>
The good news is that the user control binds and works perfectly. The javascript shows (sets the style to "display:block;") and hides (style set to "display:none;") the appropriate DIV each time the '+' is clicked.
Here is my problem: there is a 'Reply' link in the user control that, when clicked, does a post-back and puts the control into Edit mode. When I employ this user control on another page without a containing DIV, you won't notice a thing. However, when the 'Reply' does its post-back, the containing DIV reverts back to style="display:none;".
Can you provide a recommendation how to set the parent DIV's style to "display:block;" while a user is obviously working with it? I would imagine the appropriate code would go in the code behind of the user control when it goes into Edit mode.
Thanks,
Rob
Update: I recognize that there is no runat=server in my DIV. Since I'm trying to establish a dynamic ID for each, I get an error if I try to use the runat. That is probably the reason why I can't reach it from code behind...
I am very happy of myself... (see the YouTube video for this phrase, you'll be glad you did.)
In summary, this is what I added:
1. New Javascript function to add the name of the target DIV to a hidden field (The "collapseExpand" function is in the Site.Master. I couldn't put "load_div_to_hidden" in the Site.Master since "myhiddenField" isn't set up on every page
2. New hidden field to capture the name of the target DIV
3. New Javascript function to run on window.onload, check if we've got a post-back, and then display the value from the hidden field
4. Adding second Javascript call from the href in the link
Below are the new snippets of code:
<script type="text/javascript">
function load_div_to_hidden(obj) {
var hidden = document.getElementById('<%= myhiddenField.ClientID %>');
hidden.value = obj;
}
function windowOnLoad() {
var isPostBack = (('<%= IsPostBack %>').toLowerCase() == 'true') ? true : false;
if (isPostBack == true) {
var hid_field_value = document.getElementById('<%= myhiddenField.ClientID %>').value;
var right_div = document.getElementById(hid_field_value);
right_div.style.display = "block";
}
}
window.onload = windowOnLoad;
</script>
<input type="hidden" id="myhiddenField" runat="server" value="" />
<a href="<%#"javascript:collapseExpand('Order_Notes_Panel123456'); javascript:load_div_to_hidden('Order_Notes_Panel123456');" %>" >+</a>
<div id='Order_Notes_Panel123456' style="display:none;">
<uc:Comments_Control id="Comments_Control_ID" runat="server" Parent_ID='123456'/>
</div>
Works like a charm!
I have added textbox on the page that Jquery to create a datepicker. The problem is that, the textbox doesn't hold the value after a postback. After researching, I found the following solution which works perfectly, i.e. the textbox keeps its value after a postback.
<th>
<asp:CustomValidator ID="customStartDate" runat="server"
ErrorMessage="Start Date" Display = "None" ControlToValidate = "txtStartDate"
ValidationGroup ="HireGroup" ClientValidationFunction ="StartDate_Validate"/>
Start Date:
</th>
<td>
<asp:TextBox ID="txtStartDate" runat="server" Width = "140" ReadOnly = "true"
TabIndex = "5" CssClass = "datepicker" ></asp:TextBox>
<asp:HiddenField ID="hfDatePicker" runat="server"/>
</td>
And this is the Jquery code
//Set datePicker
function SetUpDatePicker() {
var $allDatepickers = $('.datepicker');
$.each($allDatepickers, function () {
$(this).datepicker({
showOn: "button",
buttonImage: "Images/calendar.gif",
buttonImageOnly: true,
minDate: 1,
altField: '[id*="hfDatePicker"]'
});
var $hfDatePicker = $('[id*="hfDatePicker"]');
var val = $($hfDatePicker).attr('Value');
$(this).val(val);
var len = $($hfDatePicker).attr('Value').length;
if (len > 0) {
$(this).datepicker("setDate", new Date($($hfDatePicker).attr("Value")));
}
});
}
Now I have a different type of problem. I can't use a RequiredFieldValidator for a HiddenField as I am getting an error "Hidden Field cannot be validate".
I'm tryind a CustomValidator, but the problem is that this control does acts only when the ControlToValidate is not empty.
I've checked all the property for RequiredFieldValidator and don't see something like ClientValidationFunction property.
Any suggestion on how to solve that problem?
(Based on the comment by #Richard77, I will make this an actual answer.)
You have a several options...
Instead of using a <asp:Hidden>, use a normal <asp:TextBox> but hide it using style='display:none; attribute. This will allow you to use the <asp:RequiredFieldValidator> as per your needs.
Another way to do it is using the <asp:CustomValidator> and add the ValidateEmptyText='true' attribute. This will force the validator to run the code even when the TextBox is empty.
Update - after thinking about this, I would NOT recommend the following, because it's not possible (that I can think of) to override the server-side version of the function, and therefore will leave you open to vulnerabilities. It's fine to do if you're purely using it for say visual reasons, and don't need the actual data to be checked on the server - however, this is an unusual situation.
A final option (but not one that I would necessarily recommend) is to override the function generated by ASP.NET. This would need to be placed on your page somewhere after the script link generated by ASP.NET, something like...
function RequiredFieldValidatorEvaluateIsValid(val) {
if(val.controltovalidate=="myValidatorId"){
// your coding here
} else {
return (ValidatorTrim(ValidatorGetValue(val.controltovalidate)) != ValidatorTrim(val.initialvalue))
}
}
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 a DropDownList for which I am trying to show a div OnSelectedIndexChanged but it says OBJECT REQUIRED.
I am binding the DataList in that div:
aspx:
<asp:DropDownList runat="server" ID="lstFilePrefix1" AutoPostBack="True"
OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged" >
<asp:ListItem Text="Prefix1" Value="Prefix1" />
<asp:ListItem Text="Prefix2" Value="Prefix2" />
<asp:ListItem Text="Prefix3" Value="Prefix3" />
<asp:ListItem Text="Prefix1 and Prefix2" Value="Prefix1 and Prefix2" />
<asp:ListItem Text="Prefix2 and Prefix3" Value="Prefix2 and Prefix3" />
</asp:DropDownList>
<asp:DataList ID="DataList1" runat="server" RepeatColumns="4"
CssClass="datalist1" OnItemDataBound="SOMENAMEItemBound"
CellSpacing="6" onselectedindexchanged="DataList1_SelectedIndexChanged"
HorizontalAlign="Center" Width="500px">
code behind:
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
if (lstFilePrefix1.SelectedItem.Text=="Prefix2")
{
int TotalRows = this.BindList(1);
this.Prepare_Pager(TotalRows);
Page.ClientScript.RegisterClientScriptBlock(GetType(), "JScript1", "ShowDiv('data');", true);
}
}
javascript:
function ShowDiv(obj)
{
var dataDiv = document.getElementById(obj);
dataDiv.style.display = "block";
}
What am I doing wrong?
You can use a standard ASP.NET Panel and then set it's visible property in your code behind.
<asp:Panel ID="Panel1" runat="server" visible="false" />
To show panel in codebehind:
Panel1.Visible = true;
Make the div
runat="server"
and do
if (lstFilePrefix1.SelectedValue=="Prefix2")
{
int TotalRows = this.BindList(1);
this.Prepare_Pager(TotalRows);
data.Style["display"] = "block";
}
Your method isn't working because the javascript is being rendered in the top of the body tag, before the div is rendered. You'd have to include code to tell the javascript to wait for the DOM to be completely ready to take on your request, which would probably be easiest to do with jQuery.
There are a few ways to handle rendering/showing controls on the page and you should take note to what happens with each method.
Rendering and Visibility
There are some instances where elements on your page don't need to be rendered for the user because of some type of logic or database value. In this case, you can prevent rendering (creating the control on the returned web page) altogether. You would want to do this if the control doesn't need to be shown later on the client side because no matter what, the user viewing the page never needs to see it.
Any controls or elements can have their visibility set from the server side. If it is a plain old html element, you just need to set the runat attribute value to server on the markup page.
<div id="myDiv" runat="server"></div>
The decision to render the div or not can now be done in the code behind class like so:
myDiv.Visible = someConditionalBool;
If set to true, it will be rendered on the page and if it's false it won't be rendered at all, not even hidden.
Client Side Hiding
Hiding an element is done on the client side only. Meaning, it's rendered but it has a display CSS style set on it which instructs your browser to not show it to the user. This is beneficial when you want to hide/show things based on user input. It's important to know that the element CAN be hidden on the server side too as long as the element/control has runat=server set just as I explained in the previous example.
Hiding in the Code Behind Class
To hide an element that you want rendered to the page but hidden is another simple single line of code:
myDiv.Style["display"] = "none";
If you have a need to remove the display style server side, it can be done by removing the display style, or setting it to a different value like inline or block (values described here).
myDiv.Style.Remove("display");
// -- or --
myDiv.Style["display"] = "inline";
Hiding on the Client Side with javascript
Using plain old javascript, you can easily hide the same element in this manner
var myDivElem = document.getElementById("myDiv");
myDivElem.style.display = "none";
// then to show again
myDivElem.style.display = "";
jQuery makes hiding elements a little simpler if you prefer to use jQuery:
var myDiv = $("#<%=myDiv.ClientID%>");
myDiv.hide();
// ... and to show
myDiv.show();
Another method (which it appears no-one has mentioned thus far), is to add an additional KeyValue pair to the element's Style array. i.e
Div.Style.Add("display", "none");
This has the added benefit of merely hiding the element, rather than preventing it from being written to the DOM to begin with - unlike the "Visible" property. i.e.
Div.Visible = false
results in the div never being written to the DOM.
Edit: This should be done in the 'code-behind', I.e. The *.aspx.cs file.
<div id="OK1" runat="server" style ="display:none" >
<asp:DropDownList ID="DropDownList2" runat="server"></asp:DropDownList>
</div>
vb.net code
Protected Sub DropDownList1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DropDownList1.SelectedIndexChanged
If DropDownList1.SelectedIndex = 0 Then
OK1.Style.Add("display", "none")
Else
OK1.Style.Add("display", "block")
End If
End Sub
RegisteredClientScriptBlock adds the script at the top of the page on the post-back with no assurance about the order, meaning that either the call is being injected after the function declaration (your js file with the function is inlined after your call) or when the script tries to execute the div is probably not there yet 'cause the page is still rendering. A good idea is probably to simulate the two scenarios I described above on firebug and see if you get similar errors.
My guess is this would work if you append the script at the bottom of the page with RegisterStartupScript - worth a shot at least.
Anyway, as an alternative solution if you add the runat="server" attribute to the div you will be able to access it by its id in the codebehind (without reverting to js - how cool that might be), and make it disappear like this:
data.visible = false
I was having a problem where setting element.Visible = true in my code behind wasn't having any effect on the actual screen. The solution for me was to wrap the area of my page where I wanted to show the div in an ASP UpdatePanel, which is used to cause partial screen updates.
http://msdn.microsoft.com/en-us/library/bb399001.aspx
Having the element runat=server gave me access to it from the codebehind, and placing it in the UpdatePanel let it actually be updated on the screen.
Hiding on the Client Side with javascript
Using plain old javascript, you can easily hide the same element in this manner:
var myDivElem = document.getElementById("myDiv");
myDivElem.style.display = "none";
Then to show again:
myDivElem.style.display = "";
jQuery makes hiding elements a little simpler if you prefer to use jQuery:
var myDiv = $("#<%=myDiv.ClientID%>");
myDiv.hide();
... and to show:
myDiv.show();