Call HTML control in code behind - asp.net

How can I get gridview HTML textbox value in .aspx.cs code?? E.g. :
<input id="Frequency" name="customerName" type="text" style="width: 44px" />
If i use the bellow code ,Then i can get the value on selectedIndex event.
string n = String.Format("{0}", Request.QueryString['customerName']);
I want to use bellow syntax.
TextBox_Label1 = (TextBox)e.Row.FindControl("Frequency");
i don't want to user the runat="server" on HTML control .
From Gridview i need to call a popup,Popup return a value ,I use the bellow code on javascript to do that
window.opener.document.getElementById("customerName").value = val;
window.close();
In my gridview .if i put the runat="server" then return value not set ,So i need to remove the runat="server".It also not work if i put the Asp:TextBox on Grid.Help me to Return popup value on gridview Asp:TextBox
Thanks!

Try a databinding expression:
<input id="Frequency" name="customerName" type="text" style="width: 44px"><%# String.Format("{0}", Request.QueryString["customerName"])%></input>

If you're having problems with this process and the difference is one is runat="server" and the other is not, I would suggest you need to look at your JavaScript to make sure that you have the proper element selection method. The rendered ClientID will be different from a standard html control ID. If you write your code so that the ClientID is injected into the JavaScript, you can keep the runat="server" and achieve your results. Standard html controls are not accessible from the code behind.

Related

Set the style of a parent DIV to a usercontrol

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!

regex validator, required field

I'm trying to use the regular expression validator for a numeric ID field. The field needs to be a required field of any number. Currently, I'm using:
="\d{1,}"
Shouldn't this make it so the user has to at least enter 1 digit?? If I hit the submit button with the field empty, it passes validation and posts back.. But if I enter non-numeric characters, it errors fine. If I wanted zero or more occurrences, I'd use: ="(\d{1,})?"
Why isn't this working? Do I need to use this in combination with a Required Field Validator? That would suck ><
Make sure you set the property ValidateEmptyText to true or else the CustomValidator will not fire for empty text.
EDIT: You can attach a javascript function to the CustomValidator to accomplish this since I don't think a RegularExpressionValidator will fire against an empty control. I have created a basic example to illustrate the solution:
<script type="text/javascript">
function CheckMyText(sender, args) {
var compare = RegExp("\\d{1,}");
args.IsValid = compare.test(args.Value);
return;
}
</script>
<asp:TextBox ID="txtTest" runat="server"></asp:TextBox>
<asp:Button ID="btnTest" runat="server" Text="Test" />
<asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="Error!"
ControlToValidate="txtTest" ValidateEmptyText="true"
ClientValidationFunction="CheckMyText"></asp:CustomValidator>
I have tested it and it seems to work. Leave a comment if you require further assistance.
You still need to use a RequiredFieldValidator.
I'm not sure where the user is entering the IDs, but if the input field is TextBox control why don't you use something like this:
if (tbID.Text.Length != 0)
{
//Logic goes here
}
When user clicks submit, you need to make sure that not only empty strings are captured, below is a regex that looks for any whitespace(tab,space etc) + matches if character is not a digit(0-9)
Dim FoundMatch As Boolean
Try
FoundMatch = Regex.IsMatch(SubjectString, "\Dm/rld$/\s", RegexOptions.IgnoreCase Or RegexOptions.Multiline)
'put your code here
Catch ex As ArgumentException
'syntax error in regular expression
End Try
I believe you'll need to use postback on your page, if you decide to use RequiredFieldValidator you can use above regex expression for that as well
Hth
In case someone is not using a CustomValidator then you can have a RequiredFieldValidator and RegularExpressionValidator for the same control. Found this solution here: http://forums.asp.net/t/1230931.aspx . Normally, this results in the error messages being displaced for the second validator but there is a way to fix that. You just have to set the Display property to dynamic for both the validators. Now the error messages for both the validators are displayed in the same location. Example code:
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"
ErrorMessage="ErrorMsg" ControlToValidate="controlID"
ValidationExpression="regexExpression"
Display="Dynamic"></asp:RegularExpressionValidator>
<asp:RequiredFieldValidator ID="RequiredFieldValidator7" runat="server"
ErrorMessage="ErrorMsg" ControlToValidate="controlID"
Display="Dynamic"></asp:RequiredFieldValidator>`

Using codeblocks within usercontrols

I tried using a codeblock syntax within a property sent to a web user control:
<uc1:MyControl ID="MyControl1" runat="server" SomeProperty="<%= somevalue %>"/>
The user control has the public property SomeProperty declared and also uses code block to display the property value:
<p><% = SomeProperty %></p>
The output on my page is unfortunately
<p><%= somevalue %></p>
And not the actual value. Anyone know of some workaround for this?
You are trying to assign a server side value on a server side control - this is not possible.
You can use code blocks in client side code (that doesn't have a runat="server" attribute), this of course doesn't not apply to server side controls.
Set the attribute in the code behind (ascx), before OnRender:
// In onload, pre render or other event handler
MyControl1.SomeProperty = somevalue; // C#
MyControl1.SomeProperty = somevalue ' VB.NET
Try assigning the value of the property to a Label and call the .DataBind() method on the control.

Disable backspace in textbox via javascript

I have a textbox which is extended by an Ajax Control Toolkit calendar.
I want to make it so that the user cannot edit the textbox and will have to instead use the calendar extender for input.
I have managed to block all keys except backspace!
This is what I have so far:
<asp:TextBox ID="TextBox1" runat="server" onKeyPress="javascript: return false;" onKeyDown="javascript: return false;" onPaste="javascript: return false;" />
How would I also disable backspace within the textbox using javascript?
EDIT
Made an edit since I need a solution in javascript.
EDIT
It turns out that onKeyDown="javascript: return false;" DOES work. I have no idea why it wasn't working before. I tried using a new textbox and it blocked backspaces fine. So sorry to everyone who posted an answer hoping to get some rep esp. after I marked it for bounty.
My textboxes now (seem) to block ALL keystrokes and also still work with the calendar extender.
ZX12R was close. This is the correct solution:
The TextBox is like this:
<asp:TextBox ID="TextBox1" runat="server" onKeyDown="preventBackspace();"></asp:TextBox>
and the script looks like this:
<script type="text/javascript">
function preventBackspace(e) {
var evt = e || window.event;
if (evt) {
var keyCode = evt.charCode || evt.keyCode;
if (keyCode === 8) {
if (evt.preventDefault) {
evt.preventDefault();
} else {
evt.returnValue = false;
}
}
}
}
</script>
First of all, the backspace wont come through on Key Press, so you have to use Key Down.
Can't you just use the HTML readonly="readonly" attribute?
<input type="text" name="country" value="Norway" readonly="readonly" />
<textarea rows="3" cols="25" readonly="readonly">
It should work! :)
</textarea>
How about using a label for the display and a hidden textbox to get the value back to the server?
You need to apply readonly on the client side controller ONLY, so that asp.net doesn't see it and still reads the data on postback. You can do this several ways, one of the easier if you use jQuery is to add a class to the text-boxes eg. cssclass="readonly" in question and $(".readonly").attr("readonly", true);.
As others said ReadOnly="True" will break the postback mechanism.
I believe you can get around it in your code-behind by accessing the Request object directly during PageLoad:
//assuming your textbox ID is 'txtDate'
if(Page.IsPostBack)
{
this.txtDate.Text = Request[this.txtDate.UniqueID];
}
Your other option is to allow Disabled controls to postback on the form, but this is somewhat of a security concern as readonly fields modified via script could potentially come back:
<form id="MyForm" runat="server" SubmitDisabledControls="True">
..
</form>
http://msdn.microsoft.com/en-us/library/system.web.ui.htmlcontrols.htmlform.submitdisabledcontrols.aspx
I'm not sure the impact of this property on ReadOnly (vs Enabled="False") controls but it's worth trying.
And finally - I did run into the same issue you're having a few years ago, and from what I remember there is a difference between using an html input marked as readonly and runat="server", and an actual serverside control where ReadOnly="true".
I have a feeling doing:
<input type="text" readonly="readonly" runat="server" id="myTextBox" />
may have still allowed the data to come through, although in the code-behind you have to treat the control as a HtmlInputText or HtmlGenericControl vs. a TextBox. You can still access the properties you need though.
Just a few ideas anyway...
here is a possible solution... add an event listener...
<asp:TextBox ID="TextBox1" runat="server" onKeyPress="KeyCheck;" />
and then the function can be like this..
function KeyCheck(e) {
var KeyID = (window.event) ? event.keyCode : e.keyCode;
if (KeyID == 8 ) {
alert('no backspaces!!);
}
}
doubt if it has to be onkeypress or onkeyup...
ReadOnly attribute does not help. The backspace still is taking your browser to back page even if your text box is read only..
use regular text boxes not read-only and not Disabled, just use client-side JavaScript to ignore keypresses.
This will ignore all keypress so you will have your READONLY behaviour and it will also ignore the backspace.
<input type="text" value="Your Text Here" onkeydown="return false;" />
No Need to call any function and all just try this:
<asp:TextBox runat="server" ID="txt" onkeydown="return false;"
onpaste = "return false;" onkeypress="return false;" />
I was able to do something similar, with Jquery. Just putting it out here for reference!
$("#inputID").keypress(function (e)
{e.preventDefault();});
$("#inputID").keydown(function (e)
{e.preventDefault();});
the first prevents keypresses, while the second prevents key down events.
Still a JS noob, so feel free to point out good / bad things with this.

Access an asp:hiddenfield control in JavaScript

What is the best way to access an ASP.NET HiddenField control that is embedded in an ASP.NET PlaceHolder control through JavaScript? The Visible attribute is set to false in the initial page load and can changed via an AJAX callback.
Here is my current source code:
<script language="javascript" type="text/javascript">
function AccessMyHiddenField()
{
var HiddenValue = document.getElementById("<%= MyHiddenField.ClientID %>").value;
//do my thing thing.....
}
</script>
<asp:PlaceHolder ID="MyPlaceHolder" runat="server" Visible="false">
<asp:HiddenField ID="MyHiddenField" runat="server" />
</asp:PlaceHolder>
EDIT: How do I set the style for a div tag in the ascx code behind in C#? This is the description from the code behind: CssStyleCollection HtmlControl.Style
UPDATE: I replaced the asp:hiddenfield with an asp:label and I am getting an "undefined" when I display the HiddenValue variable in a alert box. How would I resolve this.
UPDATE 2: I went ahead and refactored the code, I replaced the hidden field control with a text box control and set the style to "display: none;". I also removed the JavaScript function (it was used by a CustomValidator control) and replaced it with a RequiredFieldValidator control.
My understanding is if you set controls.Visible = false during initial page load, it doesn't get rendered in the client response.
My suggestion to solve your problem is
Don't use placeholder, judging from the scenario, you don't really need a placeholder, unless you need to dynamically add controls on the server side. Use div, without runat=server. You can always controls the visiblity of that div using css.
If you need to add controls dynamically later, use placeholder, but don't set visible = false. Placeholder won't have any display anyway, Set the visibility of that placeholder using css. Here's how to do it programmactically :
placeholderId.Attributes["style"] = "display:none";
Anyway, as other have stated, your problems occurs because once you set control.visible = false, it doesn't get rendered in the client response.
If the Visibility is set to false server-side, the placeholder won't be rendered and you won't be able to access anything inside it from JavaScript. Your code should work when the placeholder is visible="true"
Get rid of the placeholder, leave the hidden field empty at first, after the search populate it.
Try this:
function popup(lid)
{
var linkid=lid.id.toString();
var lengthid=linkid.length-25;
var idh=linkid.substring(0,parseInt(lengthid));
var hid=idh+"hiddenfield1";
var gv = document.getElementById("<%=GridViewComplaints.ClientID %>");
var gvRowCount = gv.rows.length;
var rwIndex = 1;
var username=gv.rows[rwIndex].cells[1].childNodes[1].innerHTML;
var prdid=gv.rows[rwIndex].cells[3].childNodes[1].innerHTML;
var msg=document.getElementById(hid.toString()).value;
alert(msg);
document.getElementById('<%= Labelcmpnme.ClientID %>').innerHTML=username;
document.getElementById('<%= Labelprdid.ClientID %>').innerHTML=prdid;
document.getElementById('<%= TextBoxviewmessage.ClientID %>').value=msg;
return false;
}
<ItemTemplate>
<asp:LinkButton ID="LabelComplaintdisplayitem" runat ="server" Text='<%#Eval("ComplaintDisp").ToString().Length>5?Eval("ComplaintDisp").ToString().Substring(0,5)+"....":Eval("ComplaintDisp") %>' CommandName ="viewmessage" CommandArgument ='<%#Eval("username")+";"+Eval("productId")+";"+Eval("ComplaintDisp") %>' class='basic' OnClientClick =" return popup(this)"></asp:LinkButton>
<asp:HiddenField ID="hiddenfield1" runat ="server" Value='<%#Eval("ComplaintDisp")%>'/>
</ItemTemplate>
If the place holder visibility is set to false, it will never be rendered , and the hidden field value will be only stored in the ViewState of the page.
just one question, why are you setting the visibility of the place holder to be false , if its containing a hidden field?
Anyway one possible way to get over this issue, is adding a TextBox or Label object , and set the display CSS style of it to "none" , then in your code copy whatever you are putting in the hidden field into the textbox/lable text property, this way you can easily read the value using javascript , since the textbox/label will be rendered but not visible to others, though this might not be that safe thing to do.
Instead of making ".visible=false", change the style to "display: none;". That will render your control but make it invisible.
Visible doesn't actually make it visible, you can leave it default. Just runat="server" and use its .Value.

Resources