Loop through all html checkboxes in form - c#

I would like to be able loop through all the html checkboxes in my form and if it is checked do something else do something else. I also would like to do this in the code behind not using any Javascript\jquery.
<form id="form1" runat="server">
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<div>
<table width="850" border="0" cellpadding="0" cellspacing="10" class="Copy" >
<tr>
<td valign="top"><table width="200" border="0" cellspacing="0" cellpadding="3" bgcolor="#f0f4f8">
<tr>
<td width="21"> </td>
<td width="179"><strong>CheckBoxes</strong></td>
</tr>
<tr>
<td><input runat="server" type="checkbox" name="checkbox1" id="checkbox1" /></td>
<td>checkbox1</td>
</tr>
<tr>
<td><input runat="server" type="checkbox" name="checkbox2" id="checkbox2" /></td>
<td>checkbox2</td>
</tr>
<tr>
<td><input runat="server" type="checkbox" name="checkbox3" id="checkbox3" /></td>
<td>checkbox3</td>
</tr>
</table>
</div>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
</form>
In the codebehind I have tried a couple of different ways but i am guessing since it is an HTML Input control of type Checkbox it is not working
foreach (CheckBox chk in Page.Form.Controls.OfType<CheckBox>())
{
if (chk.Checked == true)
{
Label1.Text = "we have checkboxes";
}
else
{
Label1.Text = "Still no checkboxes";
}
}

A couple of ways:
foreach (Control item in this.form1.Controls)
{
//We just need HtmlInputCheckBox
System.Web.UI.HtmlControls.HtmlInputCheckBox _cbx = item as System.Web.UI.HtmlControls.HtmlInputCheckBox;
if (_cbx != null)
{
if (_cbx.Checked)
{
//Do something:
Response.Write(_cbx.Name + " was checked.<br />");
}
}
}
or
//We just need HtmlInputCheckBox
IEnumerable<Control> _ctrls = from Control n in this.form1.Controls where n as System.Web.UI.HtmlControls.HtmlInputCheckBox != null select n;
if (_ctrls.Count() > 0)
{
foreach (System.Web.UI.HtmlControls.HtmlInputCheckBox item in _ctrls)
{
if (item.Checked)
{
//Do something:
Response.Write(item.Name + " was checked.<br/><br />");
}
}
}
Hope this helps....

If you know the ID of the CheckBoxes, you can try using: FindControl
Control.FindControl-Methode (String)
It wouldn't be a greate solution, biut try using this:
bool cFound = true;
while(cFounnd)
{
var cCheckBox = this.FindControl(...);
if(cCheckBox != null)
{
....
}
else
{
cFound = false;
}
}
EDIT:
Maybe you try this: ControlFinder

Related

DataList button fires every time the page is refreshed

I have a link button in a DataList in a shopping cart that works fine. Once they have selected the product, if they refresh the page, it will retrigger this button.
<asp:DataList runat="server" ID="rpCategories" RepeatColumns="4" RepeatDirection="Horizontal" OnItemCommand="rpCategories_ItemCommand"
ItemStyle-HorizontalAlign="Center" ClientIDMode="Static" ItemStyle-CssClass="bigLink">
<ItemTemplate>
<table>
<tr>
<td>
<div class="<%=EnrollmentPacksBottomBox %>">
<div class="enrollment1ProImage">
<img src="../../Common/Images/products/large/<%# Eval("largeImages") %>" width="250" />
</div>
<div class="enrollment1ProductName">
<%# Eval("productName") %>
</div>
<div class="enrollment1DescriptionBottom1">
<%# Eval("description") %>
</div>
<div class="enrollment1Price">
<table>
<tr>
<td>
<%# String.Format(CultureInfo.GetCultureInfo(MyCulture), "{0:c}", Eval("price")) %>
</td>
<td>
<div class="enrollment1PvSpacer"></div>
</td>
<td>PV:
<%# Eval("pv") %>
</td>
</tr>
</table> <%-- new amount, and buttons- start--%>
<table class="cartButtonsHolder">
<tr>
<td>
<div class="">
<button type="button" style="border: none; background-color: white;">
<table class="cartButtons">
<tr>
<td rowspan="2">
<asp:TextBox runat="server" ID="quantityHolder" Text='<%# Eval("quantity") %>' CssClass="QuantityBox"/>
</td>
<td>
<asp:LinkButton runat="server" ID="upButton" OnClick="AddItem" CssClass="caretButton fas fa-caret-up" Text="" />
</td>
</tr>
<tr>
<td>
<asp:LinkButton runat="server" ID="downButton" OnClick="SubtractItem" CssClass="caretButton fas fa-caret-down fa-m" Text="" />
</td>
</tr>
</table>
</button>
</div>
</td>
<td>
<asp:LinkButton runat="server" OnClick="SelectPro1Bottom"><div class="enrollment1SelectButton"> Add to Cart</div></asp:LinkButton>
</td>
</tr>
</div>
</div>
</td>
</tr>
</table>
</ItemTemplate>
</asp:DataList>
The code behind looks like this:
protected void SelectPro1Bottom(object sender, EventArgs e)
{
DAL oDal = new DAL();
var btn = (LinkButton)sender;
//var btn = (HtmlButton)sender;
var item = (DataListItem)btn.NamingContainer; //RepeaterItem
int index = item.ItemIndex;
int quantity = 0;
GetSelected(index);
Session["amount"] = 1;
//pull in the quantity
Quantities = Session["formatQuantities"] as List<int>;
List<OrderUserTypeHolder> TempHolder = new List<OrderUserTypeHolder>();
OrderUserTypeHolder oh = new OrderUserTypeHolder();
TempHolder = Session["userTypeHolder"] as List<OrderUserTypeHolder>;
int userType = 0;
int hasAutoship = 0;
string country = "";
userType = TempHolder[0].UserType;
hasAutoship = TempHolder[0].HasAutoship;
country = TempHolder[0].Country;
ProductIdList.Clear();
using (oDal)
{
//dist
if (userType == 2 && hasAutoship == 1)
{
SqlDataReader rd = oDal.ProductsGetAllByDescLengthAutoReader(country);
while (rd.Read())
{
ProductIdList.Add(Convert.ToInt32(rd["productId"]));
}
}
else if (userType == 2)
{
SqlDataReader rd = oDal.ProductsGetAllByDescLengthDistReader(country);
while (rd.Read())
{
ProductIdList.Add(Convert.ToInt32(rd["productId"]));
}
}
//pc
else if (userType == 3)
{
SqlDataReader rd = oDal.ProductsGetAllByDescLengthPcReader(country);
while (rd.Read())
{
ProductIdList.Add(Convert.ToInt32(rd["productId"]));
}
}
//retail
else
{
SqlDataReader rd = oDal.ProductsGetAllByDescLengthRetailReader(country);
while (rd.Read())
{
ProductIdList.Add(Convert.ToInt32(rd["productId"]));
}
}
oDal.Dispose();
}
//make sure we don't have an empty array
if (Quantities.Count > 0)
{
quantity = Quantities[index];
}
else
{
quantity = 1;
}
int productId = ProductIdList[index];
AddItemsToCart(productId, quantity, hasAutoship);
}
I have tried a wide variety of fixes including feeding a value of null to my datasource, changing my view state, and moving it inside !isPostback (the link button won't work). Every time you click the linkbutton it reloads the page (does not go in !isPostback) and refreshing the page has the same effect. Every time the page is rereshed, it will add another of the last item selected to the cart. I have tried everything I could think of and everything I have found online over the past several hours.
Any suggestions would be greatly appreciated!

How to get the hidden field value to be set within a table that uses pagination?

I have a repeater inside an html table that uses pagination. I want to be able to read the values of the hidden fields within the repeater in the code behind, but only the hidden field values of the table page being viewed on postback seem to be set when I'm in the code behind. How do I make it so the hidden field values are set for each repeater item regardless of the table page?
HTML:
<div id="divTableContainer" runat="server">
<table id="tblAssessmentExtracts" class="table table-striped table-sm table-hover ">
<thead>
<tr>
<th>Consumer</th>
<th>Assessment</th>
<th>Completed</th>
<th></th>
</tr>
</thead>
<tbody>
<asp:Repeater ID="rptAssessmentExtractQueue" runat="server" OnItemCommand="rptAssessmentExtractQueue_ItemCommand">
<ItemTemplate>
<tr class="assessment-extract-block">
<td><%# Eval("ConsumerName") %>
</td>
<td><%# Eval("SurveyName") %>
</td>
<td><%# Eval("CompletionDate") %></td>
<td class="buttoncell">
<asp:LinkButton ID="btnExportRecord" runat="server" Text="Export" CommandArgument='<%# Eval("Id") %>' />
<asp:HiddenField ID="hdAssessmentId" runat="server" Value='<%# Eval("Id") %>' />
<span class="selection"><asp:HiddenField ID="hdAssessmentSelected" runat="server" /></span>
</td>
</tr>
</ItemTemplate>
</asp:Repeater>
</tbody>
</table>
</div>
JavaScript:
<script type="text/javascript">
$(document).ready(function () {
var table = $('#tblAssessmentExtracts').DataTable({
"pageLength": 25,
});
});
function selectBlock(elementIndex, element) {
var selectedField = $(element).find('.selection input[type="hidden"]');
if ($(element).hasClass("table-info") === false) {
$(element).addClass("table-info");
}
if (selectedField.length > 0) {
selectedField.val("true");
}
}
function deselectBlock(elementIndex, element) {
var selectedField = $(element).find('.selection input[type="hidden"]');
if ($(element).hasClass("table-info")) {
$(element).removeClass("table-info");
}
if (selectedField.length > 0) {
selectedField.val("");
}
}
$('.assessment-extract-block').click(function (e) {
var selectedField = $(this).find('.selection input[type="hidden"]');
if (selectedField.length > 0) {
if (selectedField.val() === "true") {
deselectBlock(0, $(this));
} else {
selectBlock(0, $(this));
}
}
});
</script>
C#:
private IEnumerable<long> getSelectedResponses()
{
List<long> assessmentIds = new List<long>();
foreach (RepeaterItem riAssessment in rptAssessmentExtractQueue.Items)
{
HiddenField hdAssessmentSelected = riAssessment.FindControl("hdAssessmentSelected") as HiddenField;
HiddenField hdAssessmentId = riAssessment.FindControl("hdAssessmentId") as HiddenField;
bool export = false;
if (bool.TryParse(hdAssessmentSelected.Value, out export) && export)
{
long assessmentId;
if (long.TryParse(hdAssessmentId.Value, out assessmentId) && assessmentId > 0)
{
assessmentIds.Add(assessmentId);
}
}
}
return assessmentIds;
}

ASP.NET Paging next page button does not work properly

I'am trying to divide all of my products that i listed by using a repeater to pages. For example there are 3 pages. The paging looks well but when i click to next page button it is going to page 4 which is not exist actually. What can be the reason ? Implementation is below.
private void showShoes()
{
dataInThePage = new PagedDataSource()
{
DataSource = ap.getShoes(),
AllowPaging = true,
PageSize = 2,
CurrentPageIndex = pageNo
};
shoeRepeater.DataSource = dataInThePage;
shoeRepeater.DataBind();
pageAmount = dataInThePage.PageCount - 1;
//
pageInfoLabel.Text = "Page: " + (dataInThePage.CurrentPageIndex + 1) + "/" + dataInThePage.PageCount + " - Number of Shoes: " + (dataInThePage.DataSourceCount);
//
previousButton.Enabled = !dataInThePage.IsFirstPage;
nextButton.Enabled = !dataInThePage.IsLastPage;
}
private int pageNo
{
get
{
if (ViewState["pageNumber"] != null)
return Convert.ToInt32(ViewState["pageNumber"]);
return 0;
}
set
{
ViewState["pageNumber"] = value;
}
}
private int pageAmount
{
get
{
if (ViewState["pageNumber"] != null)
return Convert.ToInt32(ViewState["pageNumber"]);
return 0;
}
set { ViewState["pageNumber"] = value; }
}
public PagedDataSource dataInThePage { get; set; }
protected void previousButton_Click(object sender, EventArgs e)
{
pageNo -= 1;
showShoes();
}
protected void nextButton_Click(object sender, EventArgs e)
{
pageNo += 1;
showShoes();
}
Front-end:
<ajaxToolkit:TabPanel ID="TabPanel5" runat="server">
<HeaderTemplate>Show Shoes</HeaderTemplate>
<ContentTemplate runat="server">
<asp:Repeater ID="shoeRepeater" runat="server">
<HeaderTemplate></HeaderTemplate>
<ItemTemplate>
<table border="1" style="border-color:#ff9900; width:400px; font-weight:bold; font-family:'Oswald', Arial, sans-serif;">
<tr>
<td rowspan="6" style="width:150px; height:150px;">
<image src="shoeImages/<%#DataBinder.Eval(Container.DataItem,"ImagePath") %>"></image>
</td>
</tr>
<tr>
<td>
<%#DataBinder.Eval(Container.DataItem,"BrandName") %> - <%#DataBinder.Eval(Container.DataItem,"ModelName") %>
</td>
</tr>
<tr>
<td>
Price: $<%#DataBinder.Eval(Container.DataItem,"Price") %>
</td>
</tr>
<tr>
<td>
Size: <%#DataBinder.Eval(Container.DataItem,"Size") %>
</td>
</tr>
<tr>
<td>
Color: <%#DataBinder.Eval(Container.DataItem,"PrimaryColor") %> - <%#DataBinder.Eval(Container.DataItem,"SecondaryColor") %>
</td>
</tr>
<tr>
<td>
Quantity: <%#DataBinder.Eval(Container.DataItem,"Quantity") %>
</td>
</tr>
</table>
</ItemTemplate>
<FooterTemplate></FooterTemplate>
</asp:Repeater>
<div style="width:600px; height:20px;">
<div style="width:50px; height:100%; float:left">
<asp:Button ID="previousButton" runat="server" OnClick="previousButton_Click" Text="<<" Width="50px"/>
</div>
<div style="width:500px; height:100%; float:left; text-align:center">
<asp:Label ID="pageInfoLabel" runat="server" Text=" "></asp:Label>
</div>
<div style="width:50px; height:100%; float:left">
<asp:Button ID="nextButton" runat="server" OnClick="nextButton_Click" Text=">>" Width="50px"/>
</div>
</div>
</ContentTemplate>
</ajaxToolkit:TabPanel>
I had to guess on a number of things, but I was able to take the posted code and get it to work in VS 2010 using an ASP.NET 4.0 project.
Here are the things I did to get it working:
Add a Shoe POCO with the 8 public properties referenced in the .aspx page (not shown)
Add a FakeShoeRepository class that has a private static List<Shoe> with 9 shoes (not shown)
Add a static method called getShoes() that returns a reference to the private member variable of the repository (not shown)
Set the dataInThePage.DataSource = FakeShoeRepository.getShoes() (not shown)
Add a Page_Load() event
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
pageNo = 0;
showShoes();
}
}
Remove the pageAmount property
Remove the one place pageAmount was being set in the showShoes() method (this was effectively setting ViewState["pageNumber"] = PageCount - 1)
The last two items are where the actual problem was in the provided code.

c# postback dropdownlist always choose first value

I want to insert the selected item of drop down list into database but my drop down list keep returns the first option . auto post back is false .
codes here :
dropTask() = drop down list where I populate it from database.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
dropTask();
}
}
protected void AjaxFileUpload1_UploadComplete(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)
{
String pathdirectory = (dropListActivity.SelectedItem.Text+"/");
String filepathImage = (pathdirectory + e.FileName);
EnsureDirectoriesExist(pathdirectory);
AjaxFileUpload1.SaveAs(Server.MapPath(filepathImage));
Session["filepathImage"] = filepathImage;
}
i had checked the value return from drop down list using label :
protected void btnDone_Click(object sender, EventArgs e)
{
if (Session["filepathImage"] != null)
{
string filepathImage = Session["filepathImage"] as string;
Label1.Text = filepathImage;
}
}
the label text show the first option of the drop down list value instead of the choice I have chosen . Please enlighten me on this .
ASPX:
<tr>
<td>
<h2>Upload your Story!</h2>
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
</asp:ToolkitScriptManager>
</td>
</tr>
<tr>
<td colspan = "2"></td>
</tr>
<tr>
<td>
<b>Select Activity:</b>
</td>
<td>
<asp:DropDownList ID="dropListActivity" runat="server"
onselectedindexchanged="dropListActivity_SelectedIndexChanged">
</asp:DropDownList>
</td>
</tr>
<tr>
<td colspan = "2"></td>
</tr>
<tr>
<td>
<b>Story Title:</b>
</td>
<td>
<asp:TextBox ID="txtStoryTitle" runat="server"
ontextchanged="txtTitle_TextChanged" AutoPostBack="True"></asp:TextBox>
</td>
</tr>
<tr>
<td class="style1">
<b>Upload your files here:</b><br />
Multiple Images and 1 Audio file only.
</td>
<td class="style1">
<asp:AjaxFileUpload ID="AjaxFileUpload1" runat="server"
onuploadcomplete="AjaxFileUpload1_UploadComplete"
/>
</td>
</tr>
<tr>
<td colspan = "2"></td>
</tr>
<tr>
<td>
<asp:Label ID="Label1" runat="server" ></asp:Label>
</td>
<td>
<asp:Button ID="btnDone" runat="server" Text="Done" onclick="btnDone_Click" />
</td>
</tr>
DropListActivity.SelectedItem.ToString should do the trick. There are a few other things you should keep in mind:
Make sure you are not populating the dropdownlist on a postback.
Selected value will only be available at the sever if the portion of
the page containing the dropdownlist control is posted back.i.e if
you are using an update panel your dropdownlist should be present
within that panel or if you are posting back the entire page then there wont be any problem at all provided you meet the first criteria.
Your event handler dropListActivity_SelectedIndexChanged will
always be fired when a page is posted back and the seleceted index
has changed. The event handler dropListActivity_SelectedIndexChanged will be called after the page_load subroutine is executed.
I assume you need something like:
private void SaveSelected()
{
ViewState["SelectedItem"] = dropListActivity.SelectedItem;
}
which you use on dropListActivity_SelectedIndexChanged and
private void LoadSelected()
{
if (ViewState["SelectedItem"] != null)
dropListActivity.SelectedItem = (ListItem)ViewState["SelectedItem"];
}
which you call after dropTask();
Please, refer to this post's answer
in dropListActivity_SelectedIndexChanged event do like
if(dropListActivity.Items.Count > 0)
{
ViewState["DropDownSelectedValue"] = dropListActivity.Item.SelectedValue;
}
and on Load or databind of drop down list event write
if(ViewState["DropDownSelectedValue"] != null && dropListActivity.Items.Count > 0)
{
dropListActivity.SelectedValue = ViewState["DropDownSelectedValue"].ToString();
}

ASP.net - Unsure on how to generate table

Given the following HTML:
<asp:content id="Content1" contentplaceholderid="mainContent" runat="server">
<div class="scrollRow">
<table width="100%">
<tr>
<td width="25%">Site name: <b>My site</b></td>
<td>Created on 12th Aug 2010</td>
<td align="right"><button onclick="doRevert(1)">Revert to this</button></td>
</tr>
</table>
</div>
<div class="scrollRow">
<table width="100%">
<tr>
<td width="25%">Site name: <b>Another site</b></td>
<td>Created on 3rd Aug 2010</td>
<td align="right"><button onclick="doRevert(1)">Revert to this</button></td>
</tr>
</table>
</div>
<div class="scrollRow scrollRowOn">
<table width="100%">
<tr>
<td width="25%">Site name: <b>Another site</b></td>
<td>Created on 3rd Aug 2010</td>
<td align="right"></td>
</tr>
</table>
</div>
</asp:content>
Which is a list of rows, how am I programatically meant to generate these after I have retrieved the SQL rows from the code behind? Do I need to make my own control, or something along those lines?
Try something along these lines:
<asp:Repeater ID="Repeater1" runat="server" OnItemDataBound="Repeater1_OnItemDataBound">
<ItemTemplate>
<div class='<%# SetClass(Eval("SiteId")) %>'>
<table width="100%">
<tr>
<td width="25%">Site name: <b><%# Eval("SiteName") %></b></td>
<td>Created on <%# DataBinder.Eval(Container.DataItem, "CreateDate", "{0:dd MMM yyyy}")%></td>
<td align="right"><button id="btnRevert" runat="server" onclick="doRevert(1)">Revert to this</button></td>
</tr>
</table>
</div>
</ItemTemplate>
</asp:Repeater>
In the codebehind Repeater1_OnItemDataBound event you could set the button to be visible or not, depending on whether the item is the current one.
protected void Repeater1_OnItemDataBound(object sender, RepeaterItemEventArgs e)
{
RepeaterItem item = e.Item;
if (item.ItemType == ListItemType.AlternatingItem || item.ItemType == ListItemType.Item)
{
Site site = e.Item.DataItem as Site; //List<Site> is what you are binding to the repeater
if (site.SiteId == currentSiteId)
{
var btn = e.Item.FindControl("btnRevert") as Button;
if (btn != null)
{
btn.Visible = false;
}
}
}
}
CSS Classes for your items can be set like this:
protected string SetClass(object obj) {
int siteId;
if (int.TryParse(obj.ToString(), out siteId)){
if (siteId == currentSiteId) //currentSiteId determined elsewhere
{
return "scrollRow";
}
}
return "scrollRow scrollRowOn";
}
There are a lot of ways to get to this, of course, but here's one (possibly not the best, but that's subjective anyway):
Assuming C# web forms and ADO.Net, and assuming you need precisely that html, you could loop over the rows in the DataSet and output the html.
DataSet ds = {data set from your sql}
StringBuilder html = new StringBuilder();
foreach (DataRow row in DataSet.Tables[0].Rows) {
html.Append( string.Format(#"<div class=""scrollRow"">
<table width=""100%"">
<tr>
<td width=""25%"">Site name: <b>{0}</b></td>
<td>Created on {1}</td>
<td align="right"><button onclick="doRevert(1)">Revert to this</button></td>
</tr>
</table>",row["sitename"], row["createdate"]));
}
You could include the html by having an <asp:Literal> in the page code and setting the Text property.
You could also do it by creating System.Web.UI.WebControls.Table nodes in the code behind and adding TableRows and TableCells to them, using the same loop, and then adding those to the page using. Given what you've given us thus far, you seem to be adding controls to a page with a MasterPage, so you would need to add your tables to the Master's ContentPlaceHolder, which you can find and add controls to like so:
ContentPlaceHolder ph = (ContentPlaceHolder)this.Master.FindControl( "ContentPlaceHolder1" );
foreach (DataRow row in DataSet.Tables[0].Rows) {
Panel pnl = new Panel();
Table tbl = new Table();
TableRow tblrow = new TableRow();
TableCell cell1 = new TableCell();
cell1.Text = string.Format("Site name: <b>{0}</b>",row["sitename"]);
row.Cells.Add(cell1);
tbl.Rows.Add(tblrow);
pnl.Controls.Add(tbl);
ph.Controls.Add(pnl);
}
You can set properties on the TableRows and TableCells, but if you do it this way you will lose some control over the html that's generated, most notably the html ID attributes. You don't seem to be using those, so perhaps that's ok.
I would suggest the repeater control. You can use it something like this:
<asp:Repeater runat="server" id="myRepeater">
<ItemTemplate>
<div class="scrollRow scrollRowOn">
<table width="100%">
<tr>
<td width="25%">Site name: <b><% Eval("SiteName")%></b></td>
<td>Created on <% Eval("CreatedOn")%></td>
<td align="right"></td>
</tr>
</table>
</div>
</ItemTemplate>
</asp:Repeater>
Then you need to bind your data to it in the Page_Load event:
myRepeater.DataSource = myData;
myRepeater.DataBind();
Where my data is the data that you retrieve from the database.

Categories

Resources