Set Html Checkbox checked from code behind without runat=server - c#

I have checkboxes in my aspx page as :
<input type="checkbox" name="daySelectors" value="monday"/>
<input type="checkbox" name="daySelectors" value="tuesday"/>
<input type="checkbox" name="daySelectors" value="wednesday"/>
I am not using CheckBoxList control as these checkboxes are at different areas in my html and i need value of only selected checkboxes.
Now, I can get the values of selected Checkboxes using
String dayselector = Request.Form["daySelectors"];
It works fine until here. The problem is how can i make the checkboxes checked from code behind i.e. my aspx.cs page. The scenario is when i come to this page i have the checkboxes values that need to be checked by default. How can i do this using the values.
One way that comes to mind is i can trigger a jquery/ Javascript function from .cs passing in the values. In that case how can i set checkbox checked using their values from jquery.

Finally i just called a Javascript method from my .cs file using
ScriptManager.RegisterClientScriptBlock(this, typeof(string), "uniqueKey","SetCheckBox('sunday');",true)
and to the JavaScript method passed in the value of CheckBox that needs to be checked :
function SetCheckBox(value) {
$("input:checkbox[value=" + value + "]").attr("checked", true);
}

You cannot. If the control is not runat=server, you don't have access to it in code behind.

If you absolutely don't want runat="server" (but I think your reason for not wanting to use it might be based on a misconception), you can always have some custom properties in your Page class and then pump attributes (like "selected") straight into your checkbox markup...
<input type="checkbox" selected="<%=SelectedAttribute%>" .... />

In the checkbox tag:
in the codebehind:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
try
{
if (Request.Form["Archived"].ToString() == "1")
{
Session["checkboxstate"] = " checked='checked' ";
}
}
catch (Exception eee)
{
Session["checkboxstate"] = "";
}
}
}
Worked for me.

Related

Textbox.text always returns empty string in code behind c#

Well, I'm trying to do a simple command: get the text from TextBox. I've searched for that, but every answer failed for me.
In my code aspx:
<form id="form1" runat="server" method="post">
<div class="form">
<div class="form-search ngen-search-form">
<span id="search-trigger" class="form-search-submit">
<img src="Imagens/Lupa_Icon 2.png" id="lupa"/>
</span>
<asp:TextBox ID="txtBoxSearch" runat="server" CssClass="form-search-input" placeholder="Pesquise..." ViewStateMode="Enabled"/>
</div>
</div>
</form>
I have a Javascript function that verifies what key my client pressed:
$(document).keypress(function(e) {
if(e.which == 13){
if( document.getElementById("txtBoxSearch").value == "" ) return true;
else {
<% setSearch(); %>
document.getElementById("testeArv").innerHTML='<%=search.ToString()%>';
return false;
}
}// First if
});
And finally, my function setSearch() in code behind is:
public void setSearch( )
{
if( !Page.IsPostBack ) {
search = txtBoxSearch.Text;
}
}
Main mistake is about how to call codebehind method in jQuery. Take a look here
to know how to do it. Summary: you need ajax
Then you will have to keep in mind that it does Page.IsPostBack.
With !Page.IsPostBack you are saying "first page access" but when you press the button !Page.IsPostBack will be false. If you try the same example so:
public void setSearch( )
{
if(!Page.IsPostBack) {
// First page access
search = txtBoxSearch.Text;
} else {
// The page has been reloaded
search = txtBoxSearch.Text;
}
}
It will work. (The else will run)
I am not sure but I have tried it (without jQuery) with a button and the same error occurs. You want to run the function when the Enter is pressed so the page will do the reload. Take a look here.
Maybe it helps you in some way.
It's the <form> tag blocking your way to get the value in post back. Remove the <form> tag and use AutoPostBack=true for your text box. You won't need to use jQuery to catch the event and the value.
You can't call code behind code from client-side code. They execute on different machines.

How to make textbox visible when previous textbox contains text

I have a WebForm in which i need to place around 30 textboxes mainly to enter barcode scanned data. I am making only the first textbox visible and i want the next textbox to be visible only when the previous textbox is filled with some text. I tried using 'If' condition as well in the textbox on selected change but it doesn't work. Any solutions?
You should use java-script for this because if you will use server side function for this then It will go to server so many times by this your application performance also will decrease.
So create a java-script function that will accept one argument. This argument will take next text box id (text box u want to display).
call this javascript function like this:- onkeyup="calgrid(this,"TextBox2");"
pass nexttextbox id in place of TextBox2...
<script type="text/javascript" language="javascript">
function calgrid(firsttextbox,nexttextbox)
{
var id=firsttextbox.id;
var lastindex= id.lastIndexOf("_");
var strclnt=id.slice(0,lastindex+1);
var txtboxvalue=document.getElementById(firsttextbox).value;
if(txtboxvalue!="")
{
document.getElementById(strclnt+nexttextbox).style.visibility='visible';
}
else
{
document.getElementById(strclnt+nexttextbox).style.display = "none";
}
}
</script>
note:- If you will do visible=false from textbox property then we cannt do visible=true from javascript. So Set style for all textbox style="display:none"
You can resolve your problem by Jquery.
I have make a sample code where i have take four Textbox. Initially only first text box is visible in Web form, when user enter some values in first TextBox next Textbox is automatically display if Previous textbox have a value if not next textbox is not visible.
Sample code is given below :
<input type="text" />
<input type="text" />
<input type="text" />
<input type="text" />
$('input:text:not(:eq(0))').hide()
$('input').on("change paste keyup", function () {
if ($(this).val().length > 0) {
$(this).next().show();
}
else
{
$(this).next().hide();
}
});
I have made sample application for same ,please click on given link for Demo
See Demo application
It's at Client side code so its performance is so fast rather than Server Side.
Please vote me if you feel your problem is resolved by my idea.
I'd name these text boxes similarly like "textbox1", "textbox2", "textbox3" so you can easily find the index of current text box. Then you can use KeyDown event to control what will be shown and what not. This is not a working example but it should give you a good direction.
int currentIndex = 1;
private void TextBox1_KeyDown(object sender, KeyEventArgs e)
{
TextBox t = Controls["TextBox" + (currentIndex + 1).ToString()] as TextBox;
t.Visible = true;
currentIndex +=1;
}
Use can use Keydown event in your first textbox
try this code
initially set flag=1 as first textbox is going to be by default visible
private void visibleTextBox(Control c)
{
int flag = 1;
foreach (Control c1 in c.Controls)
{
if (c1.GetType() == typeof(TextBox))
{
if (flag == 1)
{
((TextBox)c1).Visible = true;
}
else
{
((TextBox)c1).Visible = false;
}
if (((TextBox)c1).Text != "")
{
flag = 1;
}
else
{
flag = 0;
}
}
}
}
Comparatively simple solution in JavaScript. The code should be somehow like this.
Define onchange event on text boxes like this:
<asp:TextBox ID="txt1" runat="server" onchange="show('txt1', 'txt2');"></asp:TextBox>
<asp:TextBox ID="txt2" runat="server" onchange="show('txt2', 'txt3');" Style="visibility: hidden;"></asp:TextBox>
Then use this JavaScript code to show the next TextBox conditionally. Put this code in the head tag of the page:
<script type="text/javascript">
function show(txtCurrent, txtNext) {
var valueCurrent = document.getElementById(txtCurrent).value;
//alert(valueCurrent);
if (valueCurrent.length > 0) {
document.getElementById(txtNext).style.visibility = 'visible';
}
else {
document.getElementById(txtNext).style.visibility = 'hidden';
}
}
</script>

asp.net select all/none checkboxes [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Javascript or Jquery to check and uncheck all checkbox
I have 12 asp:checkboxes on a page and I would like to add one which selects/deselects all of them.
What's the best way to do that?
I've seen people use jquery but I'm not very familiar with JS.
IS there a generic jquery finction to use?
<head>...
<script src="Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
...</head>
<body>...
<script type="text/javascript">
function Selectall() {
if ($('.JchkAll').is(':checked')) {
// .JchkGrid cssClass will be assigned to all other checkboxes in your control
$('.JchkGrid').attr('checked', 'true');
}
else {
$('.JchkGrid').removeAttr('checked', 'false');
}
}
</script>
<form>...
<asp:CheckBox runat="server" ID="cbSelectAll" Text="Select/Deselect All" CssClass="JchkAll" onchange="Selectall();"/>
<asp:CheckBox runat="server" ID="cbName" Text="Name" class="JchkGrid"/>
<asp:CheckBox runat="server" ID="cbModel" Text="Model" CssClass="JchkGrid"/>
...</form>
...</body>
Give your chckbox a css class and try this way
// .JchkAll is cssclass of your checkbox on which's click you need to check all Checkboxes
function Selectall() {
if ($('.JchkAll').is(':checked')) {
// .JchkGrid cssClass will be assigned to all other checkboxes in your control
$('.JchkGrid').attr('checked', 'true');
}
else {
$('.JchkGrid').removeAttr('checked', 'false');
}
}
Edit:
Also Don't forget to add this on checkbox's onchange attribute..
<asp:CheckBox runat="server" onchange="Selectall();" ID="cbSelectAll"
Text="Select/Deselect All" CssClass="JchkAll"/>
But this will give you a compiler warning...it would be better if you add it from code behind on Page_Load event like
cbSelectAll.Attributes.Add("onchange","Selectall");
First you find all the checkboxes, and then you change them. This you done on client via javascript. For example this is a function that if you call it is check all the chekboxes on a page.
function SwapCheck()
{
// find them
var allChecks = jQuery('input[type=checkbox]');
allChecks.each( function() {
jQuery(this).prop("checked", !this.checked);
// use this for jQuery ver 1.6 and before
// jQuery(this).attr("checked", !this.checked);
});
}
If you like to eliminate some checkboxs then warp them with a span, or div and use the
jQuery('#DivIDWithChecksToSelect input[type=checkbox]');
If you like to check them all you can use this code
jQuery(this).attr("checked", "checked");
Also you can use the jQuery(this).prop("checked", false); to uncheck them.
relative:
Setting "checked" for a checkbox with jQuery?
Check all CheckBoxes in GridView
About the .attr() and the .prop() read here : http://api.jquery.com/prop/
Give your checkboxes one CssClass name (chk_group in my example), and the give your check box that will change all of them another CssClass name (chk_select_all in my example)
then you can try this jQuery code
​$(document).ready(function(){
$(".chk_select_all input[type=checkbox]").click(function(){
$(".chk_group input[type=checkbox]").attr('checked', this.checked);
});
});​
Check here a working version: http://jsfiddle.net/a2XeK/
In ASP.NET WebForms, you'll have to use the selector .chk_select_all input[type=checkbox] because the rendering engine will create a with css style, and inside the span there will be the actual checkbox.
Multiple ways to do it. See which is best for you. Using JavaScript
function toggleCheckboxes(flag) {
var form = document.getElementById('groupImportForm');
var inputs = form.elements;
if(!inputs){
//console.log("no inputs found");
return;
}
if(!inputs.length){
//console.log("only one elements, forcing into an array");
inputs = new Array(inputs);
}
for (var i = 0; i < inputs.length; i++) {
//console.log("checking input");
if (inputs[i].type == "checkbox") {
inputs[i].checked = flag;
}
}
}
Hope this helps.
You can do it in the codebehind if you want. In the OnCheckedChanged event of the main checkbox, set all of the Checked variables of the checkboxes to true.

ASP.NET OnClick not firing in Repeater.ItemTemplate that has a custom control

Title is a bit of a mouthful, but I'm a bit stuck on this issue.
I have a search result page with has a custom control that has a Repeater. The ItemTemplate in the repeater is a PlaceHolder so I can construct the Item in a particular format; more specifically, I have a string of 'diseases' that come in the form of Disease1|disease2|disease3 and need to be given links for each disease.
Now for some code:
The following is the SearchResultControl.ascx
<asp:Panel ID="SearchResultPanel" runat="server" ScrollBars="Auto">
<asp:Repeater ID="Repeater1" runat="server"
onitemcreated="Repeater1_ItemCreated"
onitemcommand="Repeater1_ItemCommand">
<ItemTemplate>
<asp:PlaceHolder ID="ItemTemplatePlaceHolder" runat="server">
</asp:PlaceHolder>
</ItemTemplate>
<SeparatorTemplate>
<tr>
<td colspan="6"><hr /></td>
</tr>
</SeparatorTemplate>
</asp:Repeater>
</asp:Panel>
The code behind: SearchResultControl.ascx.cs
protected void Repeater1_ItemCreated(object sender, RepeaterItemEventArgs e)
{
if (e.Item.DataItem != null)
{
PlaceHolder placeHolder = e.Item.FindControl("ItemTemplatePlaceHolder") as PlaceHolder;
Control searchResultItem = Page.LoadControl("SearchResultItem.ascx");
DataRow row = (e.Item.DataItem as DataRowView).Row;
if (row != null)
{
string diseaseState = row["DiseaseStates"] as string;
searchResultItem.GetType().GetProperty("DiseaseStates").SetValue(searchResultItem, diseaseState, null);
placeHolder.Controls.Add(searchResultItem);
}
}
}
(Full disclosure, I got this idea from this question)
The SetValue calls the DiseaseStates property in SearchResultItem which in turn calls the following method to build the links, set the text, and the events:
private void BuildDiseaseStateLabels(string diseaseStates)
{
PlaceHolder placeHolder = FindControl("DiseaseStatePlaceHolder") as PlaceHolder;
string[] diseaseStateSplit = diseaseStates.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
int count = diseaseStateSplit.Length;
foreach (string diseaseState in diseaseStateSplit)
{
LinkButton diseaseStateLink = new LinkButton();
diseaseStateLink.Text = diseaseState;
//diseaseStateLink.Click += new EventHandler(OnDiseaseStateLinkClick);
diseaseStateLink.CommandArgument = "<%# Eval(\"PatientID\")+ \";\" + Eval(\"PatientStatus\")+ \";\" + Eval(\"Age\")+ \";\" + Eval(\"DiseaseStates\")%>";
diseaseStateLink.CommandName = "OnDiseaseStateLinkClick";
//diseaseStateLink.Command += new CommandEventHandler(OnDiseaseStateLinkClick);
placeHolder.Controls.Add(diseaseStateLink);
if (count != 0)
{
Label splitLabel = new Label();
splitLabel.Text = "|";
placeHolder.Controls.Add(splitLabel);
}
}
}
This is the layout for the SearchResultItem
<div id="SearchResultItemDiv" class="MainSearchResultItem">
<asp:PlaceHolder ID="DiseaseStatePlaceHolder" runat="server">
</asp:PlaceHolder>
</div>
Initially I tried setting the Click event, but that doesn't work at all. I then set the CommandArgument and CommandName but that didn't seem to do the trick. I figured the Command event might need to be set, but again, no luck. I should note that when a link is clicked the Repeater1_ItemCreated in SearchResultControl.ascx.cs is called. But since there is no data in e.Item.DataItem is null and I lose the results.
In one of the questions regarding the same issue, it was suggested that the OnItemCommand be added, but even that doesn't get called.
I also read A Stumper of an ASP.NET Question and A Stumper of an ASP.NET Question: SOLVED!, to no avail.
What could I possibly be doing wrong? All of the correct event hookups seem there, I'm checking for IsPostBack and not doing DataBind() again. blaaargharaggh
Help is always greatly appreciate.
I believe you're running into this issue because the LinkButton controls are recreated too late in the page lifecycle. You have to remember that when the page is posted back, the control technically does not exist anymore, so the event handler cannot be fired.
If you can recreate the LinkButton controls somewhere before the Page_Load event is reached, like OnInit for example, everything should work fine.
For simple pages the above usually works very well, but there are circumstances where recreating controls during OnInit requires a lot of overhead, such as storing counters or arrays in ViewState so you can keep track of the controls that need to be recreated after postback. In these situations I would suggest taking a look at the DynamicControlsPlaceHolder by Denis Bauer. This control is capable of persisting dynamic controls without any addtional code required, which is pretty awesome.
Here's a link to the latest version:
http://www.denisbauer.com/ASPNETControls/DynamicControlsPlaceholder.aspx
The problem might be that you're not doing the DataBind() again.
Because you're building the buttons on the fly, when the page post backs, the buttons haven't been created and are unable to work out which click event it should be firing.
Try getting rid of the IsPostBack check, so each time the page loads, you're re-build the repeater.

Fetch JS return value in server side page_load event in asp.net

I have an aspx master/content page scenario. The parent page has an IFrame which points to a child.aspx. The child.aspx has a checkbox, On page_load of child.aspx, I want to show/hide the checkbox depending on the following logic:
- if the child.aspx is opened directly, then I have to show the checkbox.
- if the child.aspx is opened in the IFrame, then I have to hide the checkbox.
Basically, I want to check in child.aspx, if it contains a parent window then hide the checkbox control otherwise show it.
I will prefer the show/hide code in codebehind in Page_load event as I have to execute some more logic depending on whether the it is opened from parent window or not.
Till now I did the following:
In child.aspx
<asp:Content ID="Content1" ContentPlaceHolderID="Main" Runat="Server">
<script language="javascript" type="text/javascript">
function DoesParentExists()
{
var bool = (parent.location == window.location)? false : true;
var HClientID ='<%=hfDoesParentExist.ClientID%>';
document.getElementById(HClientID).Value = bool;
}
</script>
<div>
<h2>Content - In IFrame</h2>
<asp:HiddenField runat="server" id="hfDoesParentExist" />
<asp:CheckBox ID="chkValid" runat="server" />
<asp:ImageButton ID="ImageButton_FillW8Online" ImageUrl="~/images/expand.gif"
OnClick="btnVerify_Click" runat="server" style="height: 11px" />
</div>
</asp:Content>
in client.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "DoesParentExists", "DoesParentExists()", true);
if (hfDoesParentExist.Value == "true")
{
chkValid.Visible = false;
}
}
Using RegisterClientScriptBlock, I get error in JS. That the object hfDoesParentExist doesn't exist 'coz the control is not yet created. Right? I tried using RegisterStartupScript but in codebehind I always get null in hidden variable. I don't want to use the on button click or something like it. I need it on page_load event only. How to resolve the issue?
This line:
document.getElementById(HClientID).Value = bool;
Should be: (lower case value)
document.getElementById(HClientID).value = bool;
Also you cannot check the value of a hidden field set by javascript register callback, in the current executing context on the server side.
I would move the logic to the client side to hide or show the checkbox. If the field must indeed be removed from the page you can do that as well with javascript.
function DoesParentExists()
{
var bool = (parent.location == window.location)? false : true;
var cehckboxId ='<%=chkValid.ClientID%>';
if(bool){
document.getElementById(cehckboxId).style.display = 'none';
}
else {
document.getElementById(cehckboxId).style.display = 'block';
}
}
You may want to wrap the checkbox with a div and hide the container also to include the label.
To do it server-side, I would rely on a querystring parameter. Have the parent page load the child page by appending ?inframe=1. Then check for that value in your Page_Load.

Categories