how to stop page from refreshing everytime a checkbox is click - c#

Okay, as simple as possible, I have a checkboxlist that has autopostback set to true and a OnSelectedIndexChanged. However, every time someone clicks a item in the checkbox, the page refreshes. How do I stop this? I've tried using UpdatedPanel(It kind of work).
<asp:CheckBoxList ID="Regions" runat="server" OnSelectedIndexChanged="Regions_SelectedIndexChanged" AutoPostBack="true" DataSourceID="SqlDataSource2" DataTextField="Regions" DataValueField="ID">
</asp:CheckBoxList>
The OnselectedIndexChange displays a div of other checkboxes beside the one checkboxlist.
protected void Regions_SelectedIndexChanged(object sender, EventArgs e)
{
string select = #"Select Facilities from [BulletinBoard].[DMHSAS\290974].[Facilities] ";
int[] ctr = new int[9];
int ctr1 = 0;
int counter = 0;
dFacilities.Style.Add("display", "block");
foreach (ListItem item in Regions.Items)
{
//Response.Write(item.Selected);
if (Regions.SelectedIndex == 0)
{
item.Selected = true;
CheckBoxList1.Visible = true;
counter++;
}
else if (item.Selected)
{
if (select.EndsWith("[Facilities] "))
{
select += "where ";
}
if (select.EndsWith(") "))
{
select += " or ";
}
select += " (Reg_ID = " + Regions.SelectedIndex + ") ";
ctr[ctr1 + 1] = Regions.SelectedIndex;
item.Selected = false;
counter++;
CheckBoxList1.Visible = true;
}
ctr1++;
}
if (counter == 0)
{
CheckBoxList1.Visible = false;
dFacilities.Style.Add("display", "none");
}
ctr1 = 0;
bool all = false;
foreach (int counter1 in ctr)
{
Regions.Items[counter1].Selected = true;
if (Regions.Items[0].Selected == true)
foreach (ListItem item in Regions.Items)
{
if (item.Selected)
{
all = true;
}
else
{
all = false;
break;
}
}
if (all == false)
{
Regions.Items[0].Selected = false;
}
}

You seem to really like the classic .NET postback workflow, but rather than continue down the webforms path of trying to hide postbacks, even though you want them because it makes the logic easier, why not just try sidestepping it just this one time? If, as you say, you want to prevent the page refresh (aka the postback) then there are a few things you can do to prevent it entirely.
At the top of your page:
<style type="text/css">
.hideme
{
display: none;
}
</style>
<script type="text/javascript>
var checkBoxes = document.getElementById("<%= Regions.ClientID %>")
.getElementsByTagName("input");
var cbListIDss = [
"<%= CheckBoxList1.ClientID %>",
"etc"
];
function toggle(i, chkElement)
{
if (chkElement.type == "checkbox") {
if (chkElement.checked) {
var cbElement = document.getElementById(cbListIDss [i]);
cbElement.className = cbElement.className.replace("hideme", "");
break;
}
}
}
for (var i = 0; i < checkBoxes.length; i++) {
checkBoxes[i].onClick += toggle(i, checkBoxes[i]);
}
</script>
Edit: Then, in your control, remove these attributes: OnSelectedIndexChanged="Regions_SelectedIndexChanged" AutoPostBack="true"
I didn't add the code for modifying the select variable in your postback method, but that can be done in js as well via a hidden input field.
Alternatively, the reason your update panel is not working is because you have
if (Regions.SelectedIndex == 1)
{
select += " where Reg_ID = 1";
dFacilities.Style.Add("display", "block");
// note the number at the end of this variable
CheckBoxList1.Style.Add("display", "block");
}
if (Regions.SelectedIndex == 2)
{
select += "where Reg_ID = 2";
dFacilities.Style.Add("display", "block");
// note the number at the end of this variable
// All of these are adding display to CheckBoxList1,
// even though it seems like these should be adding
// the display property to CheckBoxList2, 3, etc.
CheckBoxList1.Style.Add("display", "block");
}

Related

How to retain previous value for a textbox in onchange event in usercontrol

I have an user control with a few textboxes in it and how can I retain previous value of a textbox txtOne if a condition is not met in OnTextChanged event for the sum of txtA, txtB, txtC textboxes.
The variable "one" is considered as a previous value of the textbox. I have added the below code in usercontrol.
protected void txtOne_TextChanged(object sender, EventArgs e)
{
total = Convert.ToInt32(txtA.Text) + Convert.ToInt32(txtB.Text) + Convert.ToInt32(txtC.Text);
if (total > Convert.ToInt32(txtOne.Text.ToString()))
{
txtOne.Text = one.ToString();
}
}
Here "one" variable is getting value as 0. It should store previous value. Could you please give me a clue on where to store the value in "one" variable.
The code below is not in any way optimized or generalized. It is as close to your sample code as possible & designed to show you an answer based on your original code. I would suggest using comboboxes rather than textboxes, and/or using validation to make sure that the entries are all numeric. The code below doesn't go that far - it only answers your question based on the code you provided:
TextBox txtA = new TextBox();
TextBox txtB = new TextBox();
TextBox txtC = new TextBox();
int total = 0;
TextBox txtOne = new TextBox();
string newOne = "";
string someDefaultValue = "";
string lastOne = "";
if(txtA.Text.Length==0||txtB.Text.Length==0||txtC.Text.Length==0){
//user has not entered required fields -- abort
return;
}
bool isTextChanging = true;//CHANGE TO FALSE AT END OF PAGE_ONLOAD
protected void txtOne_TextChanged(object sender, EventArgs e)
{
if(!isTextChanging){
isTextChanging=true;
total = getTotal(new string[] { txtA.Text, txtB.Text, txtC.Text });
if (total > -1)
{
int totalTest = 0;
if (int.TryParse(txtOne.Text, out totalTest))
{
if (total > totalTest)
{
txtOne.Text = lastOne.Length > 0 ? lastOne : someDefaultValue;//default value for the first run when there is no last value
lastOne = newOne;//whatever the value of "one" is this time
}
}
else
{
MessageBox.Show("YOu must only enter numbers");
}
}
}
isTextChanging=false;
}
private int getTotal(string[] inputs)
{
int total = 0;
int subTotal = 0;
foreach(string input in inputs)
{
if(int.TryParse(input,out subTotal)){
total += subTotal;
}else{
MessageBox.Show("You must only enter numbers");
return -1;
}
}
return total;
}
Ok - I'm confused. It may be a language thing. Is this what you're trying to accomplish, but with textboxes instead of dropdownlists?
Front end:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="SO_Web.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div id="div_Boxes" runat="server">
</div>
</form>
</body>
</html>
Back End:
protected void Page_Load(object sender, EventArgs e)
{
createBoxes();
}
string[] boxNames = { "One", "Two", "Three" };
private void createBoxes()
{
int x = 0;
int y = 10;
Panel p = new Panel();
foreach (string name in boxNames)
{
Label l = new Label();
l.ID = "lbl_" + name;
l.Text = "Select Value " + name;
l.Style.Add("float", "left");
DropDownList c = new DropDownList();
c.ID = "cbx_" + name;
c.Items.Add("Select One");
for (int i = 1; i < 101; i++)
{
c.Items.Add(i.ToString());
}
c.SelectedIndex = 0;
c.AutoPostBack = true;
c.Style.Add("display", "block");
c.SelectedIndexChanged += cbx_Changed;
p.Controls.Add(l);
p.Controls.Add(c);
}
Label lbl_Total = new Label();
lbl_Total.Text = "Your Total:";
TextBox txt_Total = new TextBox();
txt_Total.ID = "txt_Total";
txt_Total.Width = 75;
p.Controls.Add(lbl_Total);
p.Controls.Add(txt_Total);
p.Width = 300;
p.Height = 200;
div_Boxes.Controls.Add(p);
}
protected void cbx_Changed(object sender, EventArgs e)
{
bool proceed = true;
int total = 0;
foreach (string name in boxNames)
{
DropDownList c = (DropDownList)findControl(this.Page.Controls,"cbx_" + name);
if (c.SelectedIndex == 0)
{
proceed = false;
}
else
{
total += c.SelectedIndex;
}
}
if (proceed)
{
((TextBox)findControl(this.Page.Controls,"txt_Total")).Text = total.ToString("C2");
}
}
private Control findControl(ControlCollection page, string id)
{
foreach (Control c in page)
{
if (c.ID == id)
{
return c;
}
if (c.HasControls())
{
var res = findControl(c.Controls, id);
if (res != null)
{
return res;
}
}
}
return null;
}
But you want to use texboxes and allow the user to type entries, and you want a MAX value of 110. If the user enters values under 110 for all three boxes, you want the total. If the user enters >110 for any box, you want the value reset to 100? Is that correct?

Trouble with setting a reference int

I have a page with a listing of products in a table (which is built with divs but I digress), and one column is called "Add to Shopping List" and contains a checkbox. If that checkbox is checked, then the product for that row should be placed into the user's order. On submission, the user is taken to an order review page with all the items they had selected.
The problem right now is that, even though I set the quantity of a product to "1" when the checkbox is selected, every time the form is submitted, the number of items selected for ordering is always 0.
The function that is meant to see if any items have been selected for ordering upon submission is called checkQtys:
protected bool checkQtys(ref int ItemCnt, ref ArrayList LinesToOrder)
{
Repeater locationRepeater = (Repeater)FindControl("locationRepeater");
bool validQtys = true;
string productID = "";
int qty;
qtyErrorMsg.Text = "";
qtyErrorMsgTop.Text = "";
foreach (RepeaterItem repItem in locationRepeater.Items)
{
if (repItem != null)
{
Repeater areaRepeater = (Repeater)repItem.FindControl("areaRepeater");
if (areaRepeater != null)
{
foreach (RepeaterItem skuItm in areaRepeater.Items)
{
if (skuItm != null)
{
Label SkuID = (Label)skuItm.FindControl("SkuID");
Label qtyID = (Label)skuItm.FindControl("qtyID");
PlaceHolder inner = (PlaceHolder)skuItm.FindControl("ProductTable");
if (inner != null)
{
foreach (Control ct in inner.Controls)
{
if (ct is CheckBox)
{
CheckBox lineQty = (CheckBox)ct;
Label prodID = (Label)inner.FindControl("productID");
if (lineQty.Checked)
{
productID = prodID.Text;
qty = 1;
LinesToOrder.Add(new LineItem(productID, qty));
ItemCnt++;
validQtys = true;
}
}
}
}
}
}
}
}
}
return validQtys;
}
*Note: This original was meant to check a textbox value--the "Add To Shopping List" column was originally set to take user input for specific quantities but that has been changed to the checkbox.
This is the submit function:
protected void orderSubmit(object sender, EventArgs e)
{
int ItemCnt = 0;
bool validQtys = true;
ArrayList LinesToOrder = new ArrayList();
Label lb = FindControl("order") as Label;
if (checkQtys(ref ItemCnt, ref LinesToOrder))
{
string value = checkQtys(ref ItemCnt, ref LinesToOrder).ToString();
Response.Write("value: " + value + "<br />");
if (ItemCnt == 0)
{//make sure at least one item with proper qty amount is entered before submitting the order
validQtys = false;
noItemMsg.Visible = true;
noItemMsg.Text = "<br /><br />You must order at least one item<br />";
noItemMsgTop.Visible = true;
noItemMsgTop.Text = "You must order at least one item<br />";
}
if (validQtys)
{//save the information to a session variable and send users to order review page
try
{
foreach (LineItem WorkLine in LinesToOrder)
{
lb.Text += WorkLine.SKUID + ", " + WorkLine.Qty + ";";
}
Session["orderComplete"] = lb.Text;
}
catch (Exception x)
{
Response.Write(x.Message.ToString());
}
Response.Redirect("/united-states/market/office-buildings/obproductmap/OrderReview");
}
}
}
What happens in the above function is that ItemCnt is always 0, and thus the user never can go to the order review page even if they have checked at least one of the checkboxes in the product listing table. I have no clue why this is happening--with the ref int value for ItemCnt being set in checkQtys, it should not be coming in as 0 in orderSubmit unless it is actually 0.
What am I missing?

checkbox in gridview not checked is true when submit click

checkbox in gridview not checked is flase when submit click But when i modify and update button click checked is TRUE
public void addchapselect()
{
TextBox1.Text = "";
for (int i = 0; i < gvChapter.Rows.Count; i++)
{
CheckBox chkbox = (CheckBox)gvChapter.Rows[i].Cells[0].FindControl("chkSelect");
if (chkbox != null)
{
if (chkbox.Checked)
{
TextBox1.Text += Convert.ToString(gvChapter.Rows[i].Cells[0].Text) + ",";
// ItemValueId = ItemValueId + ",";
string Name = Convert.ToString(gvChapter.Rows[i].Cells[1].Text);
}
}
chkbox.Checked = false;
}
if (TextBox1.Text != "")
TextBox1.Text = TextBox1.Text.Substring(0, TextBox1.Text.Length - 1);
}
The reason could be you are binding the Gridview on page_load function.
Bind it inside !IsPostback and it should work.
if (Page.IsPostBack)
{
//bind your grid here.
}

how to display validation summary of an asp.net page using Javascript

I have one asp.net form.
In it i have many fields which are required.
I want to display validation summary of all fields at the end of the form.
I have already checked for valid values of input controls.
Now i only want is Summary.
Here is my code for valid data input
<script language="javascript" type="text/javascript">
function userCheck(uName) {
var uName = document.getElementById(uName);
var letters = /^[A-Za-z0-9]+$/;
if (uName.value.match(letters) && uName.value.length != 0) {
uName.style.border = "2px solid #008A2E";
return true;
}
else {
uName.value = uName.value.replace(/[\W]/g, '');
uName.style.border = "2px solid #ff0000";
uName.focus();
return false;
}
}
</script>
This is just one function for username check.
I have many more to deal with.
Is there any way to display summary from all fields at the last when submit button is pressed ?
below solution is not working.
function ddlcheck(ddlclg) {
var clg = document.getElementById(ddlclg.id);
var clgname = document.getElementById('<%= LblCollegeName.ClientID %>');
clgname.style.display = "block";
clgname.innerHTML = "Selected College : " + clg.options[clg.selectedIndex].value;
clg.style.border = "1px solid #008A2E";
if (clg.options[clg.selectedIndex].value == "Select") {
clgname.style.display = "none";
clg.style.border = "1px solid #ff0000";
validationhtml = validationhtml + "<b>*</b> College" + "</br>";
}
}
above code is for dropdownlist.
function select() {
var count = 0;
var chkSelectAll = document.getElementById('<%= ChkSelectAll.ClientID %>');
var chkList = document.getElementById('<%= chk.ClientID %>').getElementsByTagName("input");
for (var i = 0; i < chkList.length; i++) {
if (chkList[i].checked == true) {
count++;
}
}
if (count == chkList.length)
chkSelectAll.checked = true;
else {
chkSelectAll.checked = false;
}
}
above code is for selected check boxes.
create a div ( errorreport) at required location validation summary give it style as you needed
After that
<script language="javascript" type="text/javascript">
var validationhtml="";
function userCheck(uName) {
var uName = document.getElementById(uName);
var letters = /^[A-Za-z0-9]+$/;
if (uName.value.match(letters) && uName.value.length != 0) {
uName.style.border = "2px solid #008A2E";
return true;
} else {
uName.value = uName.value.replace(/[\W]/g, '');
uName.style.border = "2px solid #ff0000";
uName.focus();
validationhtml=validationhtml +"uname is not correct" ;
return false;
}
}
function validationsummary() {
// if using jquery
$(".errorreport").html(validationhtml);
//for javascript
document.getelementbyid("errorreport").innerHTML = validationhtml;
if(validationhtml == "") {
return true;
} else {
return false;
}
}
</script>
and call validationsummary() on submit button click

how to check status of checkboxes in gridview columns on click of button

I have used checkbox column in gridview. I want to check status of that checkboxes. On click of a button it should be checked that if any checkbox is checked or not. If none checkbox is checked then it should display alert message that check checkbox first.
Hey, I found answer. It is as follows:
function checkBoxselectedornot()
{
var frm=document.forms['aspnetForm'];
var flag=false;
for(var i=0;i<document.forms[0].length;i++)
{
if(document.forms[0].elements[i].id.indexOf('chkDownloadSelectedEvent')!=-1)
{
if(document.forms[0].elements[i].checked)
{
flag=true
}
}
}
if (flag==true)
{
return true
}else
{
alert('Please select at least one Event.')
return false
}
}
protected void OnCheckedChanged(object sender, EventArgs e)
{
bool flag = false;
foreach (GridViewRow row in Grid_InvoiceGarden.Rows)
{
CheckBox chkItem = (CheckBox)row.FindControl("chkSelect");
if (chkItem.Checked)
flag = true;
}
if (flag == true)
{
btnUpdate.Visible = true;
}
else
{
btnUpdate.Visible = false;
}
}
if(document.getElementById('checkBoxId').checked) {
//checked
} else {
//not checked
}
edit: if you want to check all checkboxes of a form you can loop through the collection:
var inputs = document.getElementById('formId').getElementsByTagName('input');
var isChecked = false
for( var i = 0; i < inputs.length; i++) {
if(inputs[i].type == 'checkbox' && inputs[i].checked) {
isChecked = true;
}
}
if(isChecked) {
//at least one checkbox checked
}
Server side:
//in your button click event :
bool flag = false;
for( int i=0; i < gridview1.rows.count ; i++)
{
if(checkbox1.checked)
flag = true;
}
if(flag)
{
//means atleast one check box is checked
}
You will have to add some custom Javascript to your page for the client-side alert to show. Here's a method that I've written that works with a GridView called 'GridView1' (this should be the default name if you've just dragged the control onto your ASPX page):
<script type="text/javascript">
function ClientCheck() {
var valid = false;
var gv = document.getElementById("GridView1");
for (var i = 0; i < gv.all.length; i++) {
var node = gv.all[i];
if (node != null && node.type == "checkbox" && node.checked) {
valid = true;
break;
}
}
if (!valid) {
alert("Invalid. Please select a checkbox to continue.");
}
return valid;
}
</script>
You can see that it sets a variable to the GridView control to start with, then iterates through all the children in a for loop. If the child is a checkbox and it is checked, then we set the valid variable to true. If we get to the end of the iteration and no checked checkboxes are found, then valid remains false and we execute the alert.
To link this into your GridView on your ASPX page, first make the button column a TemplateField and surround the LinkButton with your client-side code. If you've used the designer to set up your columns, you can use the "Convert this field into a TemplateField" link in the column editor). Here's an example of the source you'll end up with:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="ObjectDataSource1">
<Columns>
<asp:TemplateField HeaderText="Button Field" ShowHeader="False">
<ItemTemplate>
<span onclick="return ClientCheck();">
<asp:LinkButton ID="LinkButton1" runat="server" CommandName="IDClick" Text='<%# Eval("YourDataSourceItem") %>'></asp:LinkButton>
</span>
</ItemTemplate>
</asp:TemplateField>
// ...your remaining columns...
Using the TemplateField lets us add any client-side code we like. Here we're adding a span and using onclick to call our ClientCheck method.
If you aren't bothered about the alert, you could achieve your aims by using a CustomValidator control, which executes on the server-side.
I hope this helps.
<script type="text/javascript" language="javascript">
function CheckboxSelect() {
var LIntCtr;
var LIntSelectedCheckBoxes = 0;
for (LIntCtr = 0; LIntCtr < document.forms[0].elements.length; LIntCtr++) {
if ((document.forms[0].elements[LIntCtr].type == 'checkbox') && (document.forms[0].elements[LIntCtr].name.indexOf('chkID') > -1)) {
if (document.forms[0].elements[LIntCtr].checked == true) {
LIntSelectedCheckBoxes = parseInt(LIntSelectedCheckBoxes) + 1;
}
}
}
if (parseInt(LIntSelectedCheckBoxes) == 0) {
alert('User(s) Must Be Selected For operation !');
return false;
}
}
</script>

Categories