JavaScript - ASP.net - Loop through all controls on an asp pannel - asp.net

Is there any way for me too loop though all controls on an asp.net pannel, and for each of the controls check the type to see if it is of asp type TimeInput?
The JS basicly needs to replicate this serverside VB.net code
'this is checking that something has been entered into at least one of the time input boxes
Protected Sub valCusAllTextBox_ServerValidate(ByVal source As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs) Handles valCusAllTextBox.ServerValidate
'When the Save or Submit button is clicked the Page.IsValid() command causes the "valCusAllTextBox" custom validator control
'(which was dragged on to the page) to call this event - where we do our customised error checking
args.IsValid = False 'args.IsValid is a system function
'check all controls within the Overtime Claim panel
For Each ctrl As Control In pnlOvertimeClaim.Controls
If TypeOf ctrl Is TimeInput Then
If CType(ctrl, TimeInput).TimeInMinutes <> 0 Then
args.IsValid = True
Exit For
End If
End If
Next
If txtOnCallAllow.Text.Trim() <> "" Then
args.IsValid = True
End If
If txtMealAllow.Text.Trim() <> "" Then
args.IsValid = True
End If
End Sub

you can use this script to find specific control from the panel,
Put script at the end of page,
<script type="text/javascript" language="javascript">
var pnl = document.getElementById('pnl')
var array = pnl.getElementsByTagName("a");
for (var n = 0; n < array.length; ++n) {
alert("anchor");
}
var array = pnl.getElementsByTagName("img");
for (var n = 0; n < array.length; ++n) {
alert("Image");
}
Like this is your panel and you want to iterate specific control.
<asp:Panel runat="server" ID="pnl">
<a id="sd" href=""></a>
<img src="" />
<a id="A1" href=""></a>
</asp:Panel>

Related

How to limit the texbox to accept only numbers and backspace?

I have to create a textbox which will ignore all the non numeric input.
I tried to use this code which I found in this site
Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
e.Handled = Not Char.IsDigit(e.Keychar)
End Sub
But I have a mistake in this part of the code System.Windows.Forms.KeyPressEventArgs
What am I doing wrong?
hope this helps
Sub btnDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles MyBase.KeyPress
if e.KeyChar= Chr(8)
'do something for backspace
else if e.KeyChar=(CHr(13)
'do something for enter
end if
end sub
I agree with Dai
Key stroke in ASP.net SHOULD ALWAYS be managed on the client side to avoid unecessary postback an avoid overloading server .
If you are not familiar with Javascript you can refer to this excelleent tutorial from W3School to manage the onChangeEvent of an input
http://www.w3schools.com/jsref/event_onchange.asp
If you really want to manage the key 'on fly', you can manage the 'onkeyDown' event
http://www.w3schools.com/jsref/event_onkeydown.asp
Use this in code-behind
if(Regex.IsMatch(yourStringToValidate,"^[a-zA-Z0-9\\\$]+$")
{
//Place your msg
}
else
{
//Place your validation msg
}
Try using the MaskedTextBox and set the mask to some thing like this:
maskedTextBox1.Mask = "\d*";
This code should be placed within head section of html.
I have used Jquery library to validate purpose
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#mytext').keydown(function(e) {
if (e.shiftKey) e.preventDefault();
else {
var nKeyCode = e.keyCode;
//Ignore Backspace and Tab keys
if (nKeyCode == 8 || nKeyCode == 9) return;
if (nKeyCode < 95) {
if (nKeyCode < 48 || nKeyCode > 57) e.preventDefault();
} else {
if (nKeyCode < 96 || nKeyCode > 105) e.preventDefault();
}
}
});
});
</script>
Html code
<input type="text" id="mytext">

Load DropDownList OnDemand and Expand DropDown after Postback in Asp.Net

Trying to Populate DropDownList when it is clicked (Asp.Net). I have a sample below but I can't get the DropDownList to stay expanded after it is loaded. Does anyone have a solution to load on demand from server other than using 3rd party controls?
JavaScript
<script type="text/javascript">
function LoadOnDemand(ddl) {
if (ddl != "") {
var control = document.getElementById(ddl.id);
__doPostBack(ddl.id, "LoadOnDemand");
}
}
function AfterLoadOnDemand(ddl) {
}
</script>
Markup
<body>
<form id="form1" runat="server">
<div>
<asp:Panel ID="DynamicPanel" runat="server" Width="200">
</asp:Panel>
</div>
</form>
</body>
CodeBehind
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim target As String = Page.Request.Params.Get("__EVENTTARGET")
Dim eventarg As String = Page.Request.Params.Get("__EVENTARGUMENT")
Call CreateDynamicControls()
If IsPostBack Then
If target <> "" Then
If eventarg = "LoadOnDemand" Then
Dim ctrl As Control = FindControl(target)
If ctrl IsNot Nothing Then
If TypeOf ctrl Is DropDownList Then
'Note: values would be from a database or table query.
' and some other logic. Simplified here.
Dim ddl As DropDownList = CType(ctrl, DropDownList)
ddl.Items.Clear()
ddl.Items.Add("one")
ddl.Items.Add("two")
ddl.Items.Add("three")
'remove onfocus from this control so it doen't fire again
'if they click it immediatly after loading
ddl.Attributes.Add("onfocus", "AfterLoadOnDemand(this)")
End If
'reset the LoadOnDemand for all the other DropDownList controls
For Each notFocusedControl As Control In DynamicPanel.Controls
If TypeOf notFocusedControl Is DropDownList Then
Dim ddl As DropDownList = CType(notFocusedControl, DropDownList)
If ddl.ID <> target Then
ddl.Attributes.Add("onfocus", "LoadOnDemand(this)")
End If
End If
Next
End If
End If
End If
End If
End Sub
Protected Sub CreateDynamicControls()
For i As Integer = 0 To 2
Dim ddl As New DropDownList
ddl.ID = "DropDownList" & i
ddl.Width = 150
ddl.Items.Add("Browse me..")
ddl.Attributes.Add("onfocus", "LoadOnDemand(this)")
ddl.AutoPostBack = True
ddl.EnableViewState = True
DynamicPanel.Controls.Add(ddl)
DynamicPanel.Controls.Add(New LiteralControl("<br/><br/>"))
Next
End Sub
The only way I found out how to exand it is by emulation. Here is a link (ExpandSelect) that has a JavaScript function to do exactly that.
And here is another reference link.
I added the following (initialWidth parameter) to the .js file. This keeps the expanded dropdown from shrinking smaller then the initial width of the dropdown.
function ExpandSelect(select, maxOptionsVisible, initialWidth) {
//code - see file
select.style.zIndex = "1000000";
//Added this right after the zIndex
if (dropWidth < initialWidth) {
select.style.width = initialWidth + 'px';
select2.style.width = initialWidth + 'px';
}
//code - see file
}

Pass Cancel or Update button click from popup back to parent page

I would like to get some help on a unique processing issue. I am looking for a specific solution given these constraints.
I have a popup aspx page that receives data from a parent page gridview Edit click. There is a great deal of parsing of data from parent page to pop up as the data is being translated in pop up, then sent back to parent page to be reassembled in the original text block before update.
When the popup passes the data back or is canceled, the parent page gridview is still in Edit mode.
I would like to pass the Cancel or Update button click from the popup to the parent page gridview so it can complete the update or cancel event without asking the user to click the corresponding command button link from the gridview edit mode, to Update or Cancel.
I am really looking for a tutorial, links or sample code as I want to fully understand how to do this.
UPDATE: There is also a jquery UIBlocker on the Parent page to prevent the user from returning to the page until the PopUp page processing has been completed. Below is the critical code:
PARENT Page:
function parentFunc(a) {
// Unblocks on return from popup page.
$.unblockUI({});
document.getElementById("<%=Textbox1.ClientID %>").value = a;
alert("Please complete the update by entering a Brief Description then clicking the UPDATE link!!");
}
function parentCancel(s) {
// Unblocks because of cancel from popup page.
// var a = 0;
$.unblockUI({});
alert("Please click the Cancel link to complete the Cancel process!!");
}
PARENT PAGE Code Behind, Row Updatinfg Event after building array of strings to pass to POPUP page.
' Sets up popup to open when row selected for edit is cycled.
If IsPostBack Then
If (e.Row.RowState And DataControlRowState.Edit) > 0 Then
If Session("updateComplete") <> "Y" And Session("CancelUpdate") <> "Y" Then
Dim BrowserSettings As String = "status=no,toolbar=no, scrollbars =yes,menubar=no,location=no,resizable=no," & "titlebar=no, addressbar=no, width=850, height=800"
Dim URL As String = "NewpttStringPopUp.aspx"
Dim dialog As String = URL
Dim scriptText1 As String = ("<script>javascript: var w = window.open('" & URL & "','_blank','" & BrowserSettings & "'); $.blockUI({ message: '<h1>Please translate text and click Submit...</h1>' }); </script>")
ScriptManager.RegisterStartupScript(Me, GetType(Page), "ClientScript1", scriptText1, False)
Session("updateComplete") = "N"
End If
End If
End If
POPUP Page:
function closeform() {
alert("Please click the Cancel Button at the buttom of the page to Cancel the process!!");
return "Please click the Cancel Button at the buttom of the page to Cancel the process!!";
}
function handleWindowClose() {
if ((window.event.clientX < 0) || (window.event.clientY < 0)) {
event.returnValue = "If you have made any changes to the fields without clicking the Save button, your changes will be lost.";
}
}
function callParentFunc()
{
var w = window.opener;
var a;
if (!w.closed) {
var val = w.parentFunc(a);
self.close();
}
this.window.focus()
}
function callParentCancel() {
var w = window.opener;
var s;
if (!w.closed) {
var val = w.parentCancel(s);
self.close();
}
}
POPUP.ASPX.VB code behind CANCEL BUTTON
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
' Cancel Button so that no update is processed.
' Sets flag to prevent java popup from reopening after RowUpdating event. Occurs in RowDataBound event.
'Dim s As String = "c"
Dim strScript2 As String = "callParentCancel();"
ClientScript.RegisterStartupScript(GetType(Page), "callParentCancel", strScript2.ToString, True)
Session("UpdateEnd") = "Y"
Session("CancelUpdate") = "Y"
'Response.Write("<script>window.close();</script>")
End Sub
POPUP.ASPX.VB code behind SUBMIT BUTTON
Process of building the arrary is not displayed for breivity..
Session("returnTranslation") = arReturn
' Page.PreviousPage.Focus()
Dim strScript As String = "callParentFunc();"
ClientScript.RegisterStartupScript(GetType(Page), "callParentFunc", strScript.ToString, True)
' Sets flag to prevent java popup from reopening after RowUpdating event. Occurs in RowDataBound event.
Session("updateComplete") = "Y"
Had a problem with preventing the popup from reloading. So there is an if condition in the load event. A dynamic number of controls are built on the popup as literals. So the Page Init event and Page Load event fire on non Postback to rebuild the controls.
thanks, all suggestions will be reviewed.
Your best bet is to create a JavaScript function on the parent, and use window.opener to access it from the popup:
On the parent
processGridCommand = function(command){
__doPostBack("<%= GridView1.ClientID %>", command);
return false;
}
From the child
<script type="text/javascript">
updateParentGrid = function(command){
if (window.opener){
window.opener.processGridCommand(command);
}
return false;
}
</script>
<asp:Button ID="Button1" runat="server" Text="Click" OnClientClick="return updateParentGrid('Update');" />
Handling the postback on the parent
This will trigger a postback on the parent, and overriding the RaisePostBackEvent method in the code-behind, you can handle it as needed:
protected override void RaisePostBackEvent(IPostBackEventHandler source, string eventArgument)
{
base.RaisePostBackEvent(source, eventArgument);
if (source == GridView1)
{
switch (eventArgument)
{
"Update":
//perform update logic
break;
"Cancel":
//cancel edit mode
break;
}
}
}

grid view checkbox and javascript not informing server side code?

I've got a asp.net gridview and inside of the grid view I have a check box at the header of the grid view like so:
<HeaderTemplate>
<asp:CheckBox Width="1px" ID="HeaderLevelCheckBox" AutoPostBack="true" OnCheckedChanged="SelectAllRows" runat="server" />
</HeaderTemplate>
This gives me a nice little check box at the top of the grid view...the event OnCheckedChanged calls a function called SelectAllRows that looks like this:
Public Sub SelectAllRows(ByVal sender As Object, ByVal e As System.EventArgs)
Dim gr As GridViewRow = DirectCast(DirectCast(DirectCast(sender, CheckBox).Parent, DataControlFieldCell).Parent, GridViewRow)
Dim h As CheckBox = DirectCast(gr.FindControl("HeaderLevelCheckBox"), CheckBox)
For Each Row As GridViewRow In Me.gvLineItems.Rows
Dim cb As CheckBox = CType(Row.FindControl("chkSelector"), CheckBox)
cb.Checked = h.Checked
Next
End Sub
So if I click this header checkbox it checks all of the items in the gridview, and if I uncheck it, it unchecks all the items in the gridview. This works fine...but what doesnt seem to work is if the page loads up and I check the grid view header checkbox to true and it selects all the items in the gridview, then i click a button such as a DELETE button that calls some server side code. That code simply loops through the grid view and checks if the checkbox has been checked, if it is it calls code to delete an item. Something to this effect:
For Each Row As GridViewRow In Me.gvLineItems.Rows
Dim cb As CheckBox = CType(Row.FindControl("chkSelector"), CheckBox)
Dim lID As Long = Convert.ToInt32(gvLineItems.DataKeys(Row.RowIndex).Value)
If cb IsNot Nothing AndAlso cb.Checked Then
'ok to delete
End If
Next
When I place a watch and debug on this it seems that the value cb is always false...
Even though it was set to true when I clicked the header checkbox...
What gives ???
The actual chkSelector in the grid view is for each row and it looks like this:
<ItemTemplate>
<asp:CheckBox ID="chkSelector" runat="server" onclick="ChangeRowColor(this)" />
</ItemTemplate>
Also I am already checking for postback..that is not the issue, remember chkSelector does not autopostback...
Thanks
I doubt, your gridview is rebinding on a Delete button click, because a click of the Delete button loads the page first where it will rebind and your checkbox's become unchecked again. I think you are binding your gridview some where in the page load event.
You have to do something like this
If(!Page.IsPostBack)
{
//Gridview Binding Code goes here....
}
Edit: Alternatively you can check/uncheck rows using javascript. It will save a round trip to the server side and resolve your current issue as well.
Here is complete code
<script language="javascript" type="text/javascript">
function SelectAll(spanChk,grdClientID) {
var IsChecked = spanChk.checked;
var Chk = spanChk;
Parent = document.getElementById(grdClientID);
var items = Parent.getElementsByTagName('input');
for(i=0;i<items.length;i++)
{
if(items[i].type=="checkbox")
{
items[i].checked=document.getElementById(spanChk).checked;
}
}
}
<HeaderTemplate>
<asp:CheckBox runat="server" ID="chkHeader" onclick="SelectAll('<%=chkHeader.ClientID %>, <%=yourGrid.ClientID %>') />
</HeaderTemplate>

Function that populates a dropdownlist inside a gridview edit template

I am trying to have different options for different user roles. Here is my code:
Private Function GetApprovedBy() As String
If User.Identity.Name = "officer" Then
Return "Approved by Officer"
ElseIf User.Identity.Name = "manager" Then
Return "Approved by Manager"
Else
Return String.Empty
End If
End Function
Then inside my gridview templates I have:
<EditItemTemplate>
<asp:DropDownList ID="ApprovalEdit" runat="server">
<asp:ListItem>Rejected</asp:ListItem>
<asp:ListItem Text=<%= GetApprovedBy() %>></asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
When I run the page I get
"Literal content ('<asp:ListItem Text=') is not allowed within a 'System.Web.UI.WebControls.ListItemCollection'."
Is there an alternative way of achieving this? Preferably without a DB.
Thanks in advance!!
Edit: I have also tried
<asp:ListItem><%= GetApprovedBy() %></asp:ListItem>
which failed with error 'Code blocks are not supported in this context'
careful with this: when binding (grid/list/repeater) use <%# %> and not <%= %>
here's an example of what #adrianos says:
Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.DataRow Then
Dim ddl As DropDownList = CType(e.Row.FindControl("ApprovalEdit"), DropDownList)
' and then do the binding or add some items
End If
End Sub
(vb! aaagghhh my eyes T_T)
You could create a method that runs on the Gridview RowDataBound event.
In that method, search for your drop down list by id. If you find it, check your user type (manager / officer) and add the relevant listItems programmatically.
I believe that what you want is this:
<% ddlRooms.Items.Clear();
for (int i = 1; i <= 3; i++)
{
ddlRooms.Items.Add(new ListItem(i.ToString() , i.ToString()));
}
%>
<asp:DropDownList ID="ddlRoomsCountToBook" runat="server">
</asp:DropDownList>
This is the way that I found out to add dynamic elements in an dropdownlist on a view.

Resources