DefaultButton in Repeater with textbox and button? - c#

I have a repeater, which represents a shoppingbasket. This shopping basket has an "Update quantity" and a "Delete item" button.
When you edit the quantity and click enter, I will need it to use the Update quantity button (unlike now where it uses the delete item button).
In the code I've tried fixing this by adding a "QuantityPanel" with a DefaultButton, but this doesn't solve my issue!
Any ideas?
My code:
<asp:Repeater ID="ProductBasketRepeater" runat="server"
onitemcommand="ProductBasketRepeater_ItemCommand"
onitemdatabound="ProductBasketRepeater_ItemDataBound1">
<ItemTemplate>
<tr class="BasketEntryItem">
<td class="ImageCol">
<asp:Image ID="ProductImageBox" runat="server" Width="50" />
</td>
<td class="NameCol">
<asp:HyperLink ID="ProductNameHyperlink" runat="server"></asp:HyperLink>
</td>
<td class="PriceCol">
<asp:Label ID="PriceLabel" runat="server"></asp:Label>
</td>
<td class="QuanCol">
<asp:Panel ID="QuantityPanel" runat="server" DefaultButton="UpdateQuantityBtn">
<asp:TextBox ID="QuantityBox" runat="server" Width="30px"></asp:TextBox>
<asp:LinkButton ID="UpdateQuantityBtn" runat="server" Text="Opdater" CommandName="UpdateQuantity"></asp:LinkButton>
</asp:Panel>
</td>
<td class="TotalCol">
<asp:Label ID="TotalPriceLabel" runat="server"></asp:Label><br />
<asp:Button ID="DeleteProductBtn" runat="server" Text="Slet" CommandName="Delete" />
</td>
</tr>
</ItemTemplate>
<SeparatorTemplate>
</SeparatorTemplate>
</asp:Repeater>

In case jQuery is unavailable, you can use simple JavaScript to set to set default button for any texbox:
JS Code:
function clickButton(e, buttonid){
var evt = e ? e : window.event;
var bt = document.getElementById(buttonid);
if (bt){
if (evt.keyCode == 13){
bt.click();
return false;
}
}
}
ASPX page or any simple "input" textbox:
<input name="TextBox1" type="text" id="TextBox1" onkeypress="return clickButton(event,'Button1')" />
Code begind C#:
TextBox1.Attributes.Add("onkeypress", "return clickButton(event,'" + Button1.ClientID + "')");
Do you need help with apply this code in repeater ?

Using jQuery, this piece of code will issue a programmatic click when pressing enter in the textbox:
$('input[id$=QuantityBox]').keypress(function(e) {
if (e.keyCode == 13) {
$(this).next('input[id$=UpdateQuantityBtn]').click();
}
});
Note: I saw a bit late you did not requested jquery specifically, but in you do, this should do the trick.

Related

How to set the visibility of a control in ASP.NET inside the DataList control?

I've got two asp:ImageButton. I want to hide asp:ImageButton ID="ReceiveButton" on each table cell, only if
"<%#Eval("StatusID")=="123" %> " something like this
I do not know how to write this conditional statement in .ASPX file. My code is something like this.
<td>
<%#Eval("StatusID")%>
</td>
<td align="center">
<asp:ImageButton ID="ReceiveButton" ToolTip="Receive/process this aproved PO" runat="server"
ImageUrl="~/DesktopModules/HBI_PurchaseOrder/Assets/Images/receive.png"
CommandName="CommandReceived" />
<asp:ImageButton ID="DetailButton" ToolTip="View Approved PO" runat="server"
ImageUrl="~/DesktopModules/HBI_PurchaseOrder/Assets/Images/view.png" CommandName="PODetails" />
</td>
I tried something like,
<td>
<%#Eval("StatusID")%>
</td>
<td align="center">
<%if (Eval("StatusID") == "123") { %>
<asp:ImageButton ID="ReceiveButton" ToolTip="Receive/process this aproved PO" runat="server"
ImageUrl="~/DesktopModules/HBI_PurchaseOrder/Assets/Images/receive.png"
CommandName="CommandReceived" />
<%} %>
<asp:ImageButton ID="DetailButton" ToolTip="View Approved PO" runat="server"
ImageUrl="~/DesktopModules/HBI_PurchaseOrder/Assets/Images/view.png" CommandName="PODetails" />
</td>
But it doesn't work. How to set properly the condition? Please help me.
You can use Item ItemDataBound event of DataList
protected void DatalistID_ItemDataBound(object sender, DataListItemEventArgs e)
{
HiddenField hfStatusID= e.Item.FindControl("hfStatusID") as HiddenField;
ImageButton ReceiveButton= e.Item.FindControl("ReceiveButton") as ImageButton;
if (hfStatusID!= null && ReceiveButton!=null)
{
if (hfStatusID.Value == "123") // As per your Requirement
{
ReceiveButton.Visible= false;
}
}
}
And Take a HiddenField on .aspx page as:
<asp:HiddenField ID="hfStatusID" runat="server" Value='<%#Eval("StatusID")%>'/>
Try this:
Just Add Visible='<%# Eval("StatusID").ToString().Trim()=="123" %>' to your control ReceiveButton Property.
<td>
<%#Eval("StatusID")%>
</td>
<td align="center">
<asp:ImageButton ID="ReceiveButton" ToolTip="Receive/process this aproved PO" runat="server"
ImageUrl="~/DesktopModules/HBI_PurchaseOrder/Assets/Images/receive.png"
CommandName="CommandReceived" Visible='<%# Eval("StatusID").ToString().Trim()=="123" %>' />
<asp:ImageButton ID="DetailButton" ToolTip="View Approved PO" runat="server"
ImageUrl="~/DesktopModules/HBI_PurchaseOrder/Assets/Images/view.png" CommandName="PODetails" />
</td>

Find Controls nested inside Repeater Control

I'm trying to find the values of TextBoxes which are rendered in a Repeater though a UserControl, i.e. the Repeater has a Placeholder for the UserControl, and inside the UserControl is where the TextBox markup actually exists. I've done this before with TextBoxes directly inside of a Repeater before, which was fairly straight forward, and I'm wondering why this apparently can't be accomplished the same way. Here is the Default page with the Repeater, which contains a Placeholder...
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<form class="formee">
<fieldset>
<legend>Faculty Information</legend>
<div class="grid-4-12">
<asp:Label ID="lblFirstName1" runat="server" Text="First Name"></asp:Label>
<asp:Label ID="lblFirstName2" runat="server" Text="" ></asp:Label>
<asp:Label ID ="lblSalary" runat="server" Text="" ClientIDMode="Static"></asp:Label>
</div>
<div class="grid-6-12">
<asp:Label ID="lblLastName1" runat="server" Text="Last Name"></asp:Label>
<asp:Label ID="lblLastName2" runat="server" Text=""></asp:Label>
</div>
</fieldset>
</form>
<div id="repeaterDiv">
<asp:Repeater ID="rptBudget" runat="server" ClientIDMode="Static">
<ItemTemplate>
<asp:PlaceHolder ID="phBudget" runat="server" EnableViewState="true" />
<br />
</ItemTemplate>
</asp:Repeater>
<asp:Button ID="btnAddBudgetControl" runat="server" Text="Add"
CausesValidation="false" OnClick="AddBudgetControl" CssClass="addBudgetControl"/>
<asp:Button ID="btnDisplayEntries" runat="server" Text="Display Entries" CausesValidation="false" OnClick="DisplayEntries" />
</div>
<div>
<asp:TextBox ID="txtTotalPercent" runat="server" ClientIDMode="Static"></asp:TextBox>
<asp:TextBox ID="txtGrandTotal" runat="server" ClientIDMode="Static"></asp:TextBox>
<asp:Label ID="lblCtrls" runat="server" Text=""></asp:Label>
</div>
...and the UserControl which is inserted in the place of the Placeholder...
<fieldset>
<legend>Faculty Salary Form</legend>
<table cellspacing="10" id="values">
<tr>
<td>
<asp:Label ID="lblServiceType" runat="server" Text="Service"></asp:Label>
<asp:DropDownList runat="server" ID="ddlServiceType" CssClass="serviceType" />
</td>
<td>
<asp:Label ID="lblSpeedCode" runat="server" Text="Speed Code"></asp:Label>
<asp:DropDownList runat="server" ID="ddlSpeedCode" CssClass="speedType" />
</td>
<td>
<asp:Label ID="lblPercentage" runat="server" Text="Percentage"></asp:Label>
<asp:Textbox ID="txtPercentage" runat="server" CssClass="percentCommitment" ClientIDMode="Static" EnableViewState="true" />
</td>
<td>
<asp:Label ID="lblTotal" runat="server" Text="Total"></asp:Label>
<asp:TextBox ID="txtTotal" runat="server" CssClass="amountCommitment" ClientIDMode="Static" EnableViewState="true"/>
</td>
<td>
<asp:Button ID="btnRemove" runat="server" Text="Remove Item" OnClick="RemoveItem" ClientIDMode="Static" CssClass="btnRemove" />
</td>
</tr>
<tr>
</tr>
</table>
</fieldset>
...but when the following code runs for the Display button's OnClick, I always get a null value for any and all TextBoxes (and DropDowns) in the UserControl...
protected void DisplayEntries(object sender, EventArgs e)
{
foreach (RepeaterItem repeated in rptBudget.Items)
{
TextBox txtPercentage = (TextBox)repeated.FindControl("txtPercentage");
if (txtPercentage == null)
{
lblCtrls.Text += " null; ";
}
else
{
lblCtrls.Text += txtPercentage.Text + "; ";
}
}
}
What's the best way to access these values? Thanks.
txtPercentage Textbox is located inside Usercontrol, so use the following helper method to retrieve it.
Helper Method
public static Control FindControlRecursive(Control root, string id)
{
if (root.ID == id)
return root;
return root.Controls.Cast<Control>()
.Select(c => FindControlRecursive(c, id))
.FirstOrDefault(c => c != null);
}
Usage
foreach (RepeaterItem repeated in rptBudget.Items)
{
TextBox txtPercentage =
(TextBox)FindControlRecursive(repeated, "txtPercentage");
...
}
Try loading the placeholder first and then looking for the textboxes in the placeholder:
Something like this:
pseudo
var ph = repeated.FindControl("phBudget");
var txtBox = ph.FindControl("txtPercentage");
/pseudo
You need to first get the UserControl, then use FindControl on the UC itself.

Get value inside nested repeater in dialog

I have a problem with getting the new value from the textbox inside a nested repeater. If i type static value into the Text property like this: i can get the value, but not the new value.
<ItemTemplate>
<tr>
<td width="160">
<%# Eval("index")%>
</td>
<td>
<%# Eval("Sex") %>
</td>
<td align="right">
<button id="EditPuppy" class="open-dialog" runat="server">
Rediger hvalp</button>
<juice:Button TargetControlID="EditPuppy" runat="server" />
</td>
<td align="right" width="30">
<asp:ImageButton runat="server" ID="DeletePuppy" CommandArgument='<%# Eval("dogid").ToString() %>'
OnClientClick='return confirm("Er du sikker på at du gerne vil slette denne hvalp?")'
OnCommand="DeletePuppy_Command" SkinID="DefaultDeleteButton" />
</td>
</tr>
<div id="_Default" runat="server" class="basic-dialog" title="Basic dialog" runat="server">
<asp:TextBox runat="server" ID="TextBoxPuppyName" Text="HEJ" /><!-- The textbox i am trying to get the value from -->
<asp:Button UseSubmitBehavior="false" runat="server" ID="ButtonPuppyName" CommandArgument="<%# ((RepeaterItem)Container.Parent.Parent).ItemIndex %> <-- Getting parent repaterid"
CommandName="<%# Container.ItemIndex %> <-- Getting current repeater index -->"
OnCommand="ButtonPuppyName_Command" Text="Opdater" />
</div>
<juice:Dialog TargetControlID="_Default" AutoOpen="false" runat="server" />
</ItemTemplate>
Codebehind:
protected void ButtonPuppyName_Command(object sender, CommandEventArgs e) {
int parentRepeaterItemIndex = Convert.ToInt32(e.CommandArgument);
int childRepeaterItemIndex = Convert.ToInt32(e.CommandName);
Repeater childReapter = (Repeater)RepeaterShowKuldUserList.Items[parentRepeaterItemIndex].FindControl("RepeaterShowKuldPuppyList");
TextBox name = (TextBox)childReapter.Items[childRepeaterItemIndex].FindControl("TextBoxPuppyName");
HttpContext.Current.Response.Write(name.Text);
}
Thanks for your help!. Remember getting into the repeaters work because i can get the "static" value
I think your problem is that you are calling repeater.DataBind (in the page load?) try to add !IsPostBack and then bind your data...
other option is that the viewState=false.. it should be "true"
Hope that helps,
Ran

Data lost in the postback

I need a way for a piece of data to presist across postbacks. Is there a way besides, cookies, and sessions?
I've got a listbox, when clicked, the selected index changed event takes a session which contains user id and feeds it to a method that fetches user's name, etc. Then I use FindControl method to locate a button inside the form view. I set the button's text property with data just fetched such as first and last name.
It works on the initial load, but if I click on other records in the listbox second time the text property is not set.
I did not write this code - I'm trying to make chages.
Here is the list box:
<asp:ListBox ID="lbxUpcommingEvents" runat="server" DataSourceID="odsUpcommingEvents"
Rows="6" DataTextField="Title" DataValueField="id" AutoPostBack="true"
Width="206px" OnSelectedIndexChanged="lbxUpcommingEvents_OnSelectedIndexChanged" />
Listbox'x on selected index changed:
protected void lbxUpcommingEvents_OnSelectedIndexChanged(object sender, EventArgs e)
{
pnlEventsSignUp.Visible = true;
string _selectedItemValue = lbxUpcommingEvents.SelectedValue.ToString();
LoadName();
}
protected void LoadName()
{
MembershipUser user = Membership.GetUser();
DataSetTableAdapters.MemberInfoTableAdapter da = new DataSetTableAdapters.MemberInfoTableAdapter();
Guid _memberId = Guid.Empty;
_memberId = new Guid(Session["myId"].ToString());
DataSet.MemberInfoDataTable dt = da.GetMember(_memberId);
if (dt.Rows.Count == 1)
{
DataSet.MemberInfoRow mr = dt[0];
RolloverLink rlnkSignUp = (RolloverLink)(fvEventSignUp.FindControl("rlnkSignUp"));
rlnkSignUp.Text = "I, " + mr.firstname + " " + mr.lastname + " will be attending this event.";
}
}
Here is markup for the form view where I set the RolloverLinkButton's text property.
<asp:Panel runat="server" ID="pnlEventsSignUp" visible="false">
<div class="dashedline" ></div>
<asp:FormView ID="fvEventSignUp" runat="server" DataSourceID="SqlDataSource1"
DataKeyNames="id" Width="100%" >
<ItemTemplate>
<h2>
<asp:Label Text='<%# Eval("title") %>' runat="server" ID="titleLabel" />
</h2>
<div class="itemdetails">
<br />
location:
<h3>
<asp:Label ID="locationLabel" runat="server" Text='<%# ShowLocationLink(Eval("locationname"),Eval("location")) %>' />
</h3>
<p>
<asp:Label Text='<%# Eval("starttime","{0:D}") %>' runat="server" ID="itemdateLabel" CssClass="GeneralText" />
<asp:Label Text='<%# ShowDuration(Eval("starttime"),Eval("endtime")) %>' runat="server" ID="Label1" CssClass="GeneralText" />
</p>
</div>
<div class="downloadevent">
<a href="#">
<img src="images/icon_download_event.gif" alt="Download this event to your personal calendar"
width="15" height="26" /></a><a href='<%# "events_download.ashx?EventID=" + Convert.ToString(Eval("id")) %>'>Add
this event to your personal calendar</a>
</div>
<Club:ImageThumbnail ID="thumb1" runat="server" ImageSize="Large" PhotoID='<%# Eval("photo") %>' />
<p>
<asp:Label Text='<%# Eval("description") %>' runat="server" ID="descriptionLabel" />
</p>
<div class="dashedline" ></div>
<asp:Panel ID="panel1" runat="server" CssClass="actionbuttons" Visible='<%#User.IsInRole("Administrators") %>'>
<table border="0" cellpadding="2" cellspacing="2">
<tr>
<td>
<asp:Label runat="server" ID="Label2" Text="Action<br />Required" Width="80px" />
</td>
<td>
<img src="images/RedArrow.jpg" alt="Red Arrow Right" />
</td>
<td>
<asp:CheckBox runat="server" ID="cbxCert" Height="30px" Text="Check to Confirm Attendance" /><br />
<asp:CustomValidator runat="server" ID="rfvConfirm"
ErrorMessage="You must check the box to continue" Font-Bold="true"
ForeColor="#cc0000" ClientValidationFunction="ensureChecked" /> <br />
<Club:RolloverLink ID="rlnkSignUp" runat="server"
/>
</td>
</tr>
</table>
</asp:Panel>
</ItemTemplate>
</asp:FormView>
</asp:Panel>
You can use ViewState. Since you are dynamically looking up the button, setting a property is quicker and we can then let Asp.Net find the button and set its text via one of the two methods I explain below:
public string rlnkSignUpText
{
get { return Convert.ToString(ViewState["rlnkSignUpText"] ?? "default value"); }
set { ViewState["rlnkSignUpText"] = value; }
}
Replace your code that searches for the button and assigns the text with:
rlnkSignUpText = "I, " + mr.firstname + " " + mr.lastname + " will be attending this event.";
Then use one of these methods to set the text to the control:
1) Use the control's OnPreRender event:
To render it, add OnPreRender="rlnkSignUp_PreRender" to your xaml like this:
<Club:RolloverLink ID="rlnkSignUp" runat="server" OnPreRender="rlnkSignUp_PreRender" />
Then in your codebehind:
protected void rlnkSignUp_PreRender(object sender, EventArgs e)
{
RolloverLink rlnkSignUp = (RolloverLink)sender;
rlnkSignUp.Text = rlnkSignUpText;
}
2) Bind the property and control together:
Instead of using the control's PreRender you can bind to the property with:
<Club:RolloverLink ID="rlnkSignUp" runat="server" Text='<%# rlnkSignUpText %>' />
You then need to call DataBind in your Page_PreRender() like so:
void Page_PreRender(object sender, EventArgs e)
{
DataBind();
}
Have you enabled ViewState in the control.
Enable View State

Radio buttons not working when binded with DataList control

When i tries to bind a radio button in a datalist it becomes multiselect as its name property becomes different even when i used GroupName to be same.
How can i make it act as radio button only.
<asp:DataList ID="dlRoomNo" runat="server" RepeatColumns="4">
<ItemTemplate>
<div class="orboxfour">
<ul class="boxfour">
<li>
<asp:RadioButton ID="rdoRoomNo" GroupName="roomNo"
Text='<%#Eval("Room No")%>' runat="server" />
</li>
</ul>
</div>
</ItemTemplate>
</asp:DataList>
There's a number of suggestions in the answers to this question.
I've solved it with a bit of jQuery, though the way I did it probably isn't the best way!
In my markup, I have a script block with
function SetUniqueRadioButton(current)
{
$('input:radio').attr('checked', false);
current.checked = true;
}
and then attached the script to a radio button in my code-behind in the ItemDataBound event
String uniqueRadioButtonScript;
RadioButton radioButton;
uniqueRadioButtonScript = "javascript:SetUniqueRadioButton(this);";
if (e.Row.RowType == DataControlRowType.DataRow)
{
radioButton = (RadioButton)e.Row.FindControl("MyRadioButton");
radioButton.Attributes.Add("onclick", uniqueRadioButtonScript)
}
the best option is like this:
1. Add script
function fnrad(rbtn) {
var radioList = document.getElementsByTagName("input");
for (var i = 0 ; i < radioList.length; i++) {
if (radioList[i].type == "radio") {
radioList[i].name = 'a';
radioList[i].setAttribute("Checked","");
}
}
rbtn.setAttribute("Checked", "checked");
}
Datalist will be like this:
<asp:DataList ID="dlEmails" RepeatLayout="Flow" runat="server">
<HeaderTemplate>
<table>
<tr>
<th>Select Email Address </th>
<th>Status</th>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td>
<asp:RadioButton ID="rbtnSelect" Text='<%#Eval("Emails") %>' onclick='fnrad(this);' GroupName="a" Checked='<%#Eval("Primary") %>' runat="server" /><br />
(<asp:Label ID="lblId" runat="server" Text='<%#Eval("Verified") %>'> </asp:Label>)
</td>
<td valign="middle">
<asp:Label ID="Label2" Style="display: none;" runat="server" Text='<%#Eval("Id") %>'> </asp:Label>
<asp:Label ID="Label1" runat="server" Text='<%#Eval("Main") %>'> </asp:Label>
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:DataList>

Categories

Resources