Calling div from code behind c# - c#

<blink>in condition i want to call div from html , which contains background image only, and I need to call it on just few pages
with same metadata. So how will i call that div, i tried few ways but
nothing helped me.
if (cMeta != null && cMeta.Name == "background")
{
if (cMeta.Text == "Yes")
{
Display(Div)
}
}
Thanks

Set runat="server" to div markup.
<div id="myDiv" runat="server"></div>
Now in code behind you can access the myDiv
private void DisplayDiv(bool isShow)
{
myDiv.Visible = isShow;
}
Now when you want to show it then just call this function with true value
DisplayDiv(true);
otherwise just call it with false ,if you don't want to show it.

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.

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.

How to hide a div if validation summary is available in javascript/Jquery

How to hide a div if validation summary is available in javascript/Jquery.
if(yourCondition){
$("div#mydiv").hide()
}
what is validation summary?
var validationSummary = $('#<%= this.ValidationSummary.ClientID %>');
var myDiv = $('#myDiv');
if (validationSummary.length || validationSummary.is(':visible')) {
myDiv.hide();
}
the cause for .is(':visible')is, that i don't know if an empty validationSummary renders the html-tags either or not. if not, you can leave out the .is()-check
you can use the HeaderText property to clean the HTML from inner ValidationSummary, seek in console for your content and you can see what change to erase.
I use this: create an element and call javascript function
ValidationSummary ID="vsGeral" runat="server" HeaderText="create element and call the HTML clean function destroy "
var validationSummary = $('[id$=vsGeral]');
if (validationSummary.length || validationSummary.is(':visible')) {
function destroy() {
$("[id$=vsGeral]").html("");
}
}

Categories