get the value of all the checked checkboxes on button click - asp.net

I have created a table in my .aspx file that looks like this:
Here is the code that does this:
<!-- code for generating the "add selected sessions" button -->
<table>
<tr>
<td><strong>Individual Sessions</strong></td>
<td >
<div class="addButton" style="text-align: center;">
<asp:LinkButton ID="LinkButton2" runat="server" Text="Add Selected Sessions" OnClick="btnAddToCart_Click" />
</div>
</td>
</tr>
</table>
<!-- add all the sessions for the user to select -->
<asp:Repeater ID="rptFeesSession" runat="server">
<HeaderTemplate>
<table >
</HeaderTemplate>
<ItemTemplate>
<asp:HiddenField ID="hdnIsSession" runat="server" Value='<%#Eval("isSession")%>' />
<tr runat="server" visible='<%# Eval("isSession")%>'>
<td valign="top" colspan="2" style="position: relative;">
<asp:HyperLink CssClass="siteColorFG popBtn" ID="hlFeeType" runat="server" Text='<%#Eval("title")%>' NavigateUrl="javascript:;"/>
</td>
<td valign="top">
<div class="">
<asp:CheckBox ID="LinkButton3" CommandArgument='<%#Eval("id")%>'CssClass="checkB" OnClick="btnAddToCart_Click" runat="server" Text='<%#Eval("amount", "{0:C}")%>' />
</div>
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
In my code behind file i want to capture all the checkboxes that have been checked and their respective CommandArgument values.
protected void btnAddToCart_Click(object sender, EventArgs e)
{
using (MyEntities db = new MyEntities())
{
//button was clicked. fetch all the check boxes from the rptFeesSession repeater into an int[]
}
}

There are several issues in your code (including conceptual / logic)
Item events in a Repeater should address item related things.
Click event handler has no access to CommandArgument attribute. Use Command instead.
Checkbox control doesn't support onclick event.
Checkbox events can run immediately only when there is AutoPostback="true".
If you want to refresh all repeater data on change of any checkbox then you can do something like this.
<asp:ScriptManager runat="server" ID="scriptMgr" /><%-- Strongly recommended --%>
<asp:UpdatePanel runat="server">
<ContentTemplate>
<asp:Repeater ID="rptFeesSession" runat="server">
<HeaderTemplate>
<table>
</HeaderTemplate>
<ItemTemplate>
<asp:HiddenField ID="hdnIsSession" runat="server" Value='<%#Eval("isSession")%>' />
<tr runat="server" visible='<%# Eval("isSession")%>'>
<td colspan="2" style="position: relative;">
<asp:HyperLink CssClass="siteColorFG popBtn" ID="hlFeeType" runat="server" Text='<%#Eval("title")%>' NavigateUrl="javascript:;" />
</td>
<td>
<div class="">
<asp:HiddenField runat="server" ID="hidID" Value='<%#Eval("id") %>' />
<asp:CheckBox ID="LinkButton3"
AutoPostBack="true" CssClass="checkB"
OnCheckedChanged="LinkButton3_CheckedChanged" runat="server"
Text='<%#Eval("amount", "{0:C}")%>' />
</div>
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
</ContentTemplate>
</asp:UpdatePanel>
//.cs
protected void LinkButton3_CheckedChanged(object sender, EventArgs e)
{
decimal total = 0;
using (MyEntities db = new MyEntities())
{
foreach (RepeaterItem item in rptFeesSession.Items)
{
var chk = item.FindControl("LinkButton3") as CheckBox;
if(chk!=null && chk.Checked){
string id = (item.FindControl("hidID") as HiddenField).Value;
total += decimal.Parse(chk.Text);
//do stuff
}
}
}
}

Related

Taking a textbox's text in a listview

I have a ListView, and i have an asp:TextBox in it:
<table>
<asp:ListView ID="Users" runat="server"
DataKeyNames="Email" onitemediting="Users_ItemEditing"
onitemupdating="Users_ItemUpdating">
<LayoutTemplate>
<tr>
<td style=" width:34%;border-bottom:1px solid black;">Name</td>
<td></td>
</tr>
<asp:PlaceHolder ID="itemPlaceHolder" runat="server" />
</LayoutTemplate>
<ItemTemplate>
<tr>
<td>
<%# Eval("name") %>
</td>
<td>
<asp:LinkButton ID="Edit" runat="server" CommandName="Edit">Edit</asp:LinkButton>
</td>
</tr>
</ItemTemplate>
<EditItemTemplate>
<tr>
<td>
<asp:TextBox ID="Name" runat="server" Text='<%# Bind("name") %>'></asp:TextBox>
</td>
<td>
<asp:LinkButton ID="Update" runat="server" CommandName="Update">Update</asp:LinkButton>
</td>
</tr>
</EditItemTemplate>
</asp:ListView>
</table>
when i change the text in the text box and then try to get it in the code behind like this:
protected void Users_ItemEditing(object sender, ListViewEditEventArgs e)
{
this.Users.EditIndex = e.NewEditIndex;
BindTheListView();
}
protected void Users_ItemUpdating(object sender, ListViewUpdateEventArgs e)
{
string Name=((TextBox)Users.Items[e.ItemIndex].FindControl("Name")).Text;
this.Users.EditIndex = -1;
BindTheListView();
}
*BindTheListView() Binds the listview Users, it works.
it takes the original text of the TextBox, the <%# Bind("name") %> instead of what i have just changed.
The update function is a lot longer so i put only what i think is needed. i know the Name recives the text that wast before in the textbox because the updtade function didnt work(it didnt change anything in the database) so i run debugg and i saw that Name recives what was before
How can i take the text that i have entered the textbox and not what was in it?
Thanks for the help
In User.ItemUpdating get new values from e.NewValues collection instead.
EDIT:
Use DataList instead of ListView:
<table>
<asp:DataList ID="Users" runat="server" DataKeyField="Email" OnEditCommand="Users_ItemEditing"
OnUpdateCommand="Users_ItemUpdating">
<HeaderTemplate>
<tr>
<td style="width: 34%; border-bottom: 1px solid black;">
Name
</td>
<td>
</td>
</tr>
<asp:PlaceHolder ID="itemPlaceHolder" runat="server" />
</HeaderTemplate>
<ItemTemplate>
<tr>
<td>
<%# Eval("name") %>
</td>
<td>
<asp:LinkButton ID="Edit" runat="server" CommandName="Edit">Edit</asp:LinkButton>
</td>
</tr>
</ItemTemplate>
<EditItemTemplate>
<tr>
<td>
<asp:TextBox ID="Name" runat="server" Text='<%# Bind("name") %>'></asp:TextBox>
</td>
<td>
<asp:LinkButton ID="Update" runat="server" CommandName="Update">Update</asp:LinkButton>
</td>
</tr>
</EditItemTemplate>
</asp:DataList>
</table>
Code behind:
protected void Users_ItemEditing(object sender, DataListCommandEventArgs e)
{
this.Users.EditItemIndex = e.Item.ItemIndex;
BindTheListView();
}
protected void Users_ItemUpdating(object sender, DataListCommandEventArgs e)
{
string Name = ((TextBox)e.Item.FindControl("Name")).Text;
}
on Page Load use
if (!IsPostBack)
{
BindTheListView();
}

Get fields within a panel within a repeater on button click

I have an item repeater that displays items that have been bid on by a user. The items are contained within a panel as they contain form elements to update the bid for each item individually. What I would like is for the user to be able to submit the individual item to be updated and for me to know which item they are trying to update so I can ignore all other fields when processing the update.
Right now, my repeater looks like:
<asp:Repeater ID="itemRepeater" runat="server" onitemdatabound="itemRepeater_DataBound">
<ItemTemplate>
<!-- Auction Item MASTER-->
<asp:Panel id="pnlDefaultButton" runat="server" DefaultButton="absenteeBtnBid">
<div style="position: absolute; left: 0px; top: 0px; transform: translate(0px, 236px);" class="item auction_item firearm user_item isotope-item">
<div class="item_image">
<asp:HyperLink ID="item_img_link" runat="server" Visible="False" EnableViewState="False">
<asp:Image ID="item_img" runat="server" Visible="False" EnableViewState="False" Width="224" />
</asp:HyperLink>
</div>
<div class="item_overlay">
<div class="item_buttons">
Following
<asp:Label ID="absenteeBidLabel" runat="server" Text="" CssClass="absenteePlaceBidLabel" AssociatedControlID="absenteeBid" style="font-size:11px;" Visible="false">
<asp:TextBox ID="absenteeBid" runat="server" Wrap="False" CssClass="absenteePlaceBid" placeholder="Enter Bid" />
</asp:Label>
<asp:TextBox ID="absenteeBidId" runat="server" Wrap="False" CssClass="timedPlaceBid" style="display:none;" Visible="false" />
<asp:TextBox ID="absenteeBidClose" runat="server" Wrap="False" CssClass="timedPlaceBid" style="display:none;" Visible="false" />
<asp:TextBox ID="absenteeBidSaleId" runat="server" Wrap="False" CssClass="timedPlaceBid" style="display:none;" Visible="false" />
<asp:Button runat="server" ID="absenteeBtnBid" cssClass="startbidding_button edit_button" OnClick="onclick_absenteeBid" Text="Edit Bid" />
<div class="bid_options">
Live Bid
Bid by Phone
<asp:HyperLink ID="bid_withdraw" runat="server" CssClass="withdrawbid"></asp:HyperLink>
</div>
</div>
<table class="item_bidstatus" border="0" cellpadding="0" cellspacing="0" width="190">
<tbody>
<tr>
<td class="status_label" width="50%">Bids:</td>
<td class="status_value" width="50%"><asp:Label ID="bid_count" runat="server" Text="0" /></td>
</tr>
<tr>
<td class="status_label">My Top Bid:</td>
<td class="status_value"><asp:Literal ID="bid_amount" runat="server"></asp:Literal></td>
</tr>
<tr>
<td class="status_label">Your Status:</td>
<td class="status_value status_low">LOW BID</td>
</tr>
</tbody>
</table>
<div class="item_description">
<h5>
<asp:HyperLink ID="labelLot" runat="server">Lot #<%# Eval("item_lot")%></asp:HyperLink> - <asp:HyperLink ID="item_title" runat="server"><%# Eval("item_title")%></asp:HyperLink>
</h5>
<asp:Label ID="labelEst" runat="server" Visible="false"></asp:Label>
<p class="item_details"><asp:Label ID="labelDesc" runat="server"><%# Eval("item_desc")%></asp:Label></p>
> Item Details
</div>
</div>
<table class="item_footer" width="100%">
<tbody>
<tr>
<td><div class="item_category"><asp:HyperLink ID="item_sale" runat="server"></asp:HyperLink></div></td>
<td><div class="item_daysleft">Bid left: <asp:Literal ID="bid_time" runat="server"></asp:Literal></div></td>
</tr>
</tbody>
</table>
</div>
</asp:Panel>
<!-- /Auction Item MASTER-->
</ItemTemplate>
</asp:Repeater>
So my question would be how do I make the method onclick_absenteeBid only look at the form fields within the panel where the submission was made? Or am I even going about this the right way at all using a panel within a repeater?
Thre's nothing wrong with this approach. You have to find the container panel in the button's click event and find controls inside it. Here's how you can do it:
protected void onclick_absenteeBid(object sender, EventArgs e)
{
Panel pnl = ((Button) sender).Parent as Panel;
if (pnl != null)
{
//Access controls inside panel here like this:
TextBox absenteeBidId = pnl.FindControl("absenteeBidId") as TextBox;
if(absenteeBidId != null)
{
string myAbsenteeBidId = absenteeBidId.Text;
}
//Access Repeater Item
RepeaterItem itm = pnl.NamingContainer as RepeaterItem;
if (itm != null)
{
// Do stuff
}
}
}

How to use javascript validations for controls within ListView EditTemplate?

In Nridubai website,i am using listview EditTemplate for editing purpose. In my EditTemplate, there are controls like..
<asp:TextBox ID="txtEditEventName" runat="server"
Text='<%# Bind("event_name") %>' />
And a few more controls like dropdownlist, calender controls. Now I want to validate using javascript on these controls, but its not working.
Eg.
var eventStatus=document.getElementById("<%=txtEditEventName.ClientID%>").value;
I am not using validation controls. Please help me how to use javascript for validation on EditTemplate Controls? My EditTemplate structure is like the following:
<EditItemTemplate>
<td class="command"><asp:LinkButton ID="btnCancel" runat="server" Text="Cancel" CommandName="Cancel" />
<asp:LinkButton ID="LinkButton2" runat="server" Text="Update" CommandName="Update" />
</td>
<div class="header">View Details for '<%# Eval("event_name")%>'</div>
<tr>
<td class="edit" colspan="6" >
<div class="details">
<table class="detailview" cellpadding="0" cellspacing="0">
<tr>
<td>Event Name:</td>
<td>
<asp:TextBox ID="txtEditEventName" runat="server"
Text='<%# Bind("event_name") %>' />
</td>
<td>VenueAddress :</td>
<td>
<asp:TextBox ID="txtEditVenue" runat="server" Text='<%# Bind("venue") %>' />
</td>
</tr>
<tr>
<td>Country :</td>
<td>
<asp:DropDownList ID="lstEditCountry" runat="server"
Width="174" />
</td>
<td>Event Status:</td>
<td>
<asp:DropDownList ID="lstEditStatus" runat="server" Width="175px" >
<asp:ListItem value='0' Selected="True">-Select-</asp:ListItem>
<asp:ListItem >In-Progress</asp:ListItem>
<asp:ListItem >Completed</asp:ListItem>
<asp:ListItem >Aborted</asp:ListItem>
</asp:DropDownList>
</td>
</tr>
<tr>
<td>Category :</td>
<td>
<asp:DropDownList ID="lstEditCategory" runat="server"
Width="174" />
</td>
</tr>
<tr>
<td>Start Date:</td>
<td>
<asp:TextBox ID="txtEditStartDate" runat="server"
Text='<%# Bind("start_date", "{0:dd/MM/yyyy}") %>' />
</td>
<td>End Date:</td>
<td>
<asp:TextBox ID="txtEditEndDate" runat="server"
Text='<%# Bind("end_date","{0:dd/MM/yyyy}") %>' />
</td>
</tr>
</table>
<div class="footer command">
<asp:LinkButton ID="LinkButton1" runat="server" Text="Close" CommandName="Cancel" />
</div>
</div>
</td>
</tr>
</EditItemTemplate>
You can access the elements on ItemDataBound and emit their ClientIDs for your JavaScript to use:
ItemDataBound:
protected void ListView1_ItemDataBound(object sender, ListViewItemEventArgs e)
{
StringBuilder vars= new StringBuilder();
if (ListView1.EditItem != null)
{
TextBox txtEditStartDate = ListView1.EditItem.FindControl("txtEditStartDate") as TextBox;
TextBox txtEditEndDate = ListView1.EditItem.FindControl("txtEditEndDate") as TextBox;
//example js, however I recommend passing the ClientIDs to functions
vars.Append(String.Format("var txtEditStartDate='{0}';" txtEditStartDate.ClientID);
vars.Append(String.Format("var txtEditStartDate='{0}';", txtEditEndDate.ClientID );
ClientScriptManager.RegisterStartUpScript(this.GetType(), "validationVars", vars.ToString(), true);
}
}
***Old Answer, the .NET way************
EditTemplate:
<asp:TextBox ID="txtEditEventName" runat="server"
Text='<%# Bind("event_name") %>' />
<asp:RequiredFieldValidator
id="rfvEditEventName"
ClientValidationFunction="txtEditEventNameClientValidate"
ControlToValidate="txtTitle"
runat="server"
Display="dynamic">*
</asp:RequiredFieldValidator>
JS:
function txtEditEventNameClientValidate(sender, args) {
if (args.Value == '') {
args.IsValid = false; // field is empty
//so something
}
else {
//do something
}
}
Put the validation javascript in the EditTemplate itself. This way, when it switches to edit-mode, the control will be in the context.

How to Recognize the CommandName of a LinkButton Inside an ItemTemplate af a RadListBox

I added an itemtemplate to my radlistbox and also added one label and two linkbutton(s) in it ...
my radlistbox is like below :
<telerik:RadListBox ID="RadlbOfImageGroup" runat="server" DataKeyField="ID" DataSortField="Title"
DataSourceID="sdsImagesGroup" DataTextField="Title" DataValueField="ID" Skin="BlackByMe"
EnableEmbeddedSkins="False" Width="260px" Height="365px" EmptyMessage="no rec!"
AutoPostBack="True" OnSelectedIndexChanged="RadlbOfImageGroup_SelectedIndexChanged"
CausesValidation="False">
<ItemTemplate>
<table style="width: 100%;">
<tr style="width: 100%;">
<td style="width: 64%;">
<asp:Label ID="lblTitleOfIG" runat="server" CssClass="lbl_ListBox_IG_Title" Text='<%# Eval("Title") %>'></asp:Label>
</td>
<td style="width: 18%; text-align: center;">
<asp:LinkButton ID="lbEditIG" runat="server" CausesValidation="False" CommandName="Edit"
CssClass="lb_ListBox_IG" OnClick="lbEditIG_Click">Edit</asp:LinkButton>
</td>
<td style="width: 18%; text-align: center;">
<asp:LinkButton ID="lbDeleteIG" runat="server" CausesValidation="False" CommandName="Delete"
CssClass="lb_ListBox_IG" OnClick="lbDeleteIG_Click">Delete</asp:LinkButton>
</td>
</tr>
</table>
</ItemTemplate>
</telerik:RadListBox>
My Problem is how can I check the CommandName of LinkButtons in code above when I click on them?
(We don't have access to these LinkButtons in CodeBehind)
I know we do not need CommandName for those LinkButtons / I Just want to know is it possible to read them from codebehind?
I'm not sure if this is a standard way of addressing this issue but it's what I use:
For Each item In RadlbOfImageGroup.Items
Dim editbutton As HtmlGenericControl = item.findcontrol("lbEditIG")
//Do something with editbutton.CommandName
Dim deletebutton As HtmlGenericControl = item.findcontrol("lbDeleteIG")
//Do something with deletebutton.CommandName
Next
The above example is in VB.Net but should translate fairly easily to C# if that's what you're using.
here is the code that has been introduced by telerik team :
protected void lbDeleteIG_Click(object sender, EventArgs e)
{
LinkButton btn = sender as LinkButton;
if (btn.CommandName=="Delete")
{
Response.Write("Deleted");
}
}

ASP:ListBox - no selected items on postback?

I have the following markup:
<tr>
<td valign="top" align="left">
<asp:Label ID="Label1" runat="server" Text="Available Roles" />
<br />
<asp:ListBox ID="availableRolesListBox" runat="server" SelectionMode="Multiple" Width="100px" Rows="10" AutoPostBack="false" />
</td>
<td valign="top" align="center">
<br />
<asp:Button ID="addToRole" runat="server" Text="--->" OnClick="addToRole_Click" />
<br />
<asp:Button ID="removeFromRole" runat="server" Text="<---" OnClick="removeFromRole_Click" />
</td>
<td valign="top" align="left">
<asp:Label ID="Label2" runat="server" Text="User In Roles" />
<br />
<asp:ListBox ID="userInRolesListBox" runat="server" SelectionMode="Multiple" Width="100px" Rows="10" AutoPostBack="false" />
</td>
</tr>
And the following in code-behind:
protected void addToRole_Click(object sender, EventArgs e)
{
// Add user to the selected role...
foreach (ListItem myItem in availableRolesListBox.Items)
{
if (myItem.Selected)
{
Roles.AddUserToRole(userListBox.SelectedItem.Value, myItem.Text);
}
}
Refresh();
}
When I step into the code-behind absolutely no items are selected! What am I forgetting?
Are you perhaps rebinding the availableRolesListBox each time, instead of if(!IsPostback)?
You could check a few things.
CHeck that you are NOT reloading the listbox after each postback. Also, you might want to make sure you do not have ViewStateEnabled="false" for a parent container.
Other than that your code looks like it should be ok, debugging any further would require more code or information.

Resources