I have a repeater using for getting an image nad a radio button on the bottom. I want to achieve a combination of this radio button (repeater speaking) with the property of autoexcluyent feature. How can I achieve it?
As far as I got ...
<asp:Repeater runat="server" ID="repeater1">
<ItemTemplate>
<div class="col-xs-12 col-sm-4 col-md-3">
<asp:Image ID="img" runat="server" ImageUrl="<%#GetRutaImagen(Eval("id").ToString())%>" />
<span>
<asp:RadioButton runat="server" ID="rb1" Text='<%#Eval("description").ToString()%>' GroupName="nameGroup"/>
</span>
</div>
</ItemTemplate>
</asp:Repeater>
With this code I am getting a one radio button per each image but no one autoexcuyent even I am using GroupName property
USING NET FRAMEWORK 4.6.2.
I don't know if easy way to manage this situation however you can manage by below code. It will be good to wrap your contents into update panel so you can prevent page refresh on checkbox changed.
Additionally, IsChecked property being used to initialize checked on page load. You can remove if not required.
.ASPX
<asp:Repeater runat="server" ID="repeater1">
<ItemTemplate>
<div class="col-xs-12 col-sm-4 col-md-3">
<span>
<asp:RadioButton runat="server" ID="rb1" Checked='<%# Eval("IsChecked") %>' AutoPostBack="true" OnCheckedChanged="rb1_CheckedChanged" Text='<%#Eval("description").ToString()%>' />
</span>
</div>
</ItemTemplate>
</asp:Repeater>
.CS
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
List<test1> lst = new List<test1>();
lst.Add(new test1() { Id = 1, description = "R1", IsChecked = false });
lst.Add(new test1() { Id = 3, description = "R2", IsChecked = true });
lst.Add(new test1() { Id = 2, description = "R3", IsChecked = false });
lst.Add(new test1() { Id = 4, description = "R4", IsChecked = false });
repeater1.DataSource = lst;
repeater1.DataBind();
}
}
protected void rb1_CheckedChanged(object sender, EventArgs e)
{
foreach (RepeaterItem item in repeater1.Items)
{
(item.FindControl("rb1") as RadioButton).Checked = false;
}
(sender as RadioButton).Checked = true;
}
After researching between SOF and a few forums I implemented a quite right solution using JS. I am handling another problem related with OnCheckedChanged´s event on RadioButton...
But the initial issue is fixed.
Forum Solution
I am posting the solution that works for me, using as base as a help coming from a forum, hoping it helps others as well with this bug.
REPEATER.
<asp:Repeater runat="server" ID="repeater1" OnItemDataBound="repeater1_ItemDataBound">
<ItemTemplate>
<div class="col-xs-12 col-sm-4 col-md-3">
<asp:Image ID="img" runat="server" ImageUrl="<%#GetRutaImagen(Eval("id").ToString())%>" />
<span>
<asp:RadioButton runat="server" ID="rb1" Text='<%#Eval("description").ToString()%>' GroupName="nameGroup" OnCheckedChanged="rb1_CheckedChanged"/>
</span>
</div>
</ItemTemplate>
</asp:Repeater>
JS
<script>
function SetUniqueRadioButton(nameregex, current) {
for (i = 0; i < document.forms[0].elements.length; i++) {
elm = document.forms[0].elements[i]
if (elm.type == 'radio') {
elm.checked = false;
}
}
current.checked = true;
}
</script>
BACKEND
protected void repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
try
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
RadioButton rbLogoSeleccionado = (RadioButton)e.Item.FindControl("rb1");
string script = "SetUniqueRadioButton('repeater1.*nameGroup',this)";
rbLogoSeleccionado.Attributes.Add("onclick", script);
}
}
catch (Exception ex)
{
PIPEvo.Log.Log.RegistrarError(ex);
throw;
}
}
Related
I have a webs form page and I have a text box which once clicked passes a variable to the code behind and then back into another element of that page and I cannot get it to work.
This is the closest I have got.
<asp:Panel ID="Search" runat="server" Visible="true">
<tr>
<td>
<asp:Label ID="lblSearch" runat="server" Text="Search"></asp:Label>
</td>
<td>
<asp:TextBox ID="search" runat="server" />
</td>
<td>
<asp:RequiredFieldValidator ID="valSearch" runat="server"
ControlToValidate="movieSearch" Text="Please enter text" />
</td>
<td>
<asp:Button ID="btnSubmit" runat="server" Text="Save"
OnClick="btnSubmit_Click" />
</td>
</tr>
</table>
</asp:Panel>
<asp:Panel ID="pnlSearchResult" runat="server" Visible="false">
<script>
var search = '<%=Server.UrlDecode(Request.QueryString["Data"]) %>';
</script>
</asp:Panel>
And the code behind:
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (IsValid)
{
pnlSearch.Visible = false;
pnlSearchResult.Visible = true;
Response.Redirect("search.aspx?Data=" + Server.UrlEncode(search.Text));
}
}
Also this does not change the visibility of the two panels for some reason.
I would appreciate any guidance I am very new to asp and c#.
The panel's visibility is not changing because you're forcing a new GET request to the page with this: -
Response.Redirect("search.aspx?Data=" + Server.UrlEncode(search.Text));
(I'm assuming your page is called 'search.aspx')
There's no need to do this. Remove this line.
Secondly, I see you want to force the textbox's Text value into a Javascript variable. Replace this
var search = '<%=Server.UrlDecode(Request.QueryString["Data"]) %>';
with this
var search = '<%= search.Text %>';
Write below code on page event.
Another more important point is you first panel Id is "Search" not "pnlSearch" on aspx page so please correct it
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["Data"] != null)
{
Search.Visible = false;
pnlSearchResult.Visible = true;
}
}
I recommend solution without using Response.Redirect.
Code Behind Submit Button click:
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (IsValid)
{
pnlSearch.Visible = false;
pnlSearchResult.Visible = true;
}
}
In Markup:
<asp:Panel ID="pnlSearchResult" runat="server" Visible="false">
<script>
var searchTxt = document.getElementById('search');
if(searchTxt.value != null && searchTxt.value != ''){
//do your stuff
}
</script>
From a listview control, when checkboxes are checked and a button is clicked from outside the listview, I need to be able to delete the items that have been checked. Here's the listview:
EDIT
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack) return;
var notes = (from n in db.Notes
select n).OrderBy(n => n.FiscalYear).ThenBy(n => n.Period);
notesListView.DataSource = notes;
notesListView.DataBind();
}
<asp:ListView ID="notesListView" ItemPlaceholderID="itemPlaceholder" runat="server">
<LayoutTemplate>
<div>
<asp:PlaceHolder ID="itemPlaceholder" runat="server"></asp:PlaceHolder>
</div>
</LayoutTemplate>
<ItemTemplate>
<asp:CheckBox ID="checkNote" runat="server" />
<div><%# Eval("Period") %></div>
<div><%# Eval("FiscalYear") %></div>
<div><%# Eval("Account") %></div>
<div class="wrap"><%# Eval("Description") %></div>
</ItemTemplate>
<EmptyDataTemplate>
<div>No notes have been submitted.</div>
</EmptyDataTemplate>
</asp:ListView>
<br />
<asp:Button ID="deleteNotes" CssClass="deleteButton" Text="Delete Notes" runat="server" OnClick="deleteNotes_Click" />
Here's the code behind:
protected void deleteNotes_Click(object sender, EventArgs e)
{
foreach (ListViewItem item in notesListView.Items)
{
// I know this is wrong, just not sure what to do
if (notesListView.SelectedIndex >= 0)
{
CheckBox ck = (CheckBox)item.FindControl("checkNote");
if (ck.Checked)
{
var index = item.DataItemIndex; // the item row selected by the checkbox
// db is the datacontext
db.Notes.DeleteOnSubmit(index);
db.SubmitChanges();
}
}
else
{
errorMessage.Text = "* Error: Nothing was deleted.";
}
}
}
You need to find the object before deleting it. To do so, I would add a hiddenfield to store NoteID like this:
<asp:HiddenField ID="hdnId" Value='<%#Eval("Id")%>' runat="server" />
<asp:CheckBox ID="checkNote" runat="server" />
... ... ...
And in my code I am finding the note by ID and deleting that note (You may use any other unique field instead of ID). My code may look like this:
... ... ...
int id = 0;
var hdnId = item.FindControl("hdnId") as HiddenField;
CheckBox ck = (CheckBox)item.FindControl("checkNote");
//I would check null for ck
if (ck != null && ck.Checked && hdnId != null && int.TryParse(hdnId.Value, out id)
{
// db is the datacontext
Note note = db.Notes.Single( c => c.Id== id );
db.Notes.DeleteOnSubmit(note );
db.SubmitChanges();
}
I have a repeater control as listed below. It has a textbox control. When a save button is clicked, I need to get the updated text from the textbox. I have the following code; but it gives me the old value when I take the textbox text.
How can we get the updated text?
Code Behind
protected void Save_Click(object sender, EventArgs e)
{
foreach (RepeaterItem item in repReports.Items )
{
if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem )
{
string updatedEmail = ((TextBox)item.Controls[5]).Text;
string originalEmail = ((HiddenField)item.Controls[7]).Value;
}
}
}
Control Markup
<div class="repeaterTableBorder">
<asp:Repeater ID="repReports" runat="server">
<ItemTemplate>
<div id="repeaterIdentifier" class="repeaterIdentifier">
<div class="reportTitle">
<%# Eval("ReportName") + ":"%>
<asp:HiddenField ID="hdnLastChangeTime" runat="server" Value= '<%# ((DateTime)Eval("RecordSelectionTime")).ToString("MM/dd/yyyy hh:mm:ss.fff tt")%>' />
<asp:HiddenField ID="hdnReportID" runat="server" Value='<%# Eval("ReportTypeCode")%>' />
</div>
<div class="reportFrequency">
<%# " Frequency - Weekly" %>
</div>
</div>
<div class="reportContent">
<div class="repeaterLine">
<asp:TextBox ID="txtEmailRecipients" runat="server" class="textEdit"
Text='<%# Eval("ExistingRecipients") %>'
TextMode="MultiLine"></asp:TextBox>
<asp:HiddenField ID="hdnOriginalRecipients" runat="server" Value='<%# Eval("ExistingRecipients")%>' />
</div>
</div>
</ItemTemplate>
</asp:Repeater>
</div>
I assume that you are binding the Repeater to it's DataSource also on postbacks. You should do that only if(!IsPostBack). Otherwise the values will be overwritten.
protected void Page_Load(Object sender, EventArgs e)
{
if(!IsPostBack)
{
// databinding code here
}
}
I have a repeater for different updates identified by "Update_ID". Each "Update_ID" has a number of images associated to it.
Therefore, I decided to nest a repeater for the images inside the repeater for updates.
The problem is that the image repeater never shows up, even if there is data to show.
Here is the code in ASP.NET:
<asp:Repeater ID="RepeaterUpdates" runat="server" onitemcommand="RepeaterUpdates_ItemCommand">
<ItemTemplate>
<div style="border: thin solid #808080">
<table id="TableUpdates_Repeater" runat="server" style="width:100%; margin:auto; background-image:url(Resources/Icons/white-background.gif)">
<tr>
<td style="width:25%">
<br />
<asp:Label ID="LabelUpdateID_Repeater" runat="server" Text="Update ID" Enabled="false"></asp:Label>
<asp:TextBox ID="TextBoxUpdateID_Repeater" runat="server" Width="50px" Text='<%# Eval("Update_ID") %>' Enabled="false"></asp:TextBox>
</td>
</tr>
</table>
<asp:Repeater ID="RepeaterImages" runat="server">
<ItemTemplate>
<label>Hello</label>
<asp:TextBox Text='<%# DataBinder.Eval(Container.DataItem,"Image_ID") %>' runat="server"></asp:TextBox>
</ItemTemplate>
</asp:Repeater>
</div>
</ItemTemplate>
</asp:Repeater>
Here is the code-behind:
protected void RepeaterUpdates_ItemCommand(object source, RepeaterCommandEventArgs e)
{
SqlConnection conn5 = new SqlConnection(connString);
SqlDataReader rdr5;
RepeaterItem item = e.Item;
TextBox Update_ID = (TextBox)item.FindControl("TextBoxUpdateID_Repeater");
try
{
conn5.Open();
SqlCommand cmd5 = new SqlCommand("SelectImages", conn5);
cmd5.CommandType = CommandType.StoredProcedure;
cmd5.Parameters.Add(new SqlParameter("#update_id", Update_ID.Text));
rdr5 = cmd5.ExecuteReader();
if ((item.ItemType == ListItemType.Item) || (item.ItemType == ListItemType.AlternatingItem))
{
Repeater ImageRepeater = (Repeater)item.FindControl("RepeaterImages");
ImageRepeater.DataSource = rdr5;
ImageRepeater.DataBind();
}
}
finally
{
conn5.Close();
}
}
As previously stated, the child repeater never shows up, even if there is data to display. How can I solve this problem please? Thanks
Rather than onitemcommand, call OnItemDataBound
Change RepeaterCommandEventArgs to RepeaterItemEventArgs
In addition to #Curt. Below is the code.
Code Behind
class Images
{
public int Image_ID;
}
protected void RepeaterUpdates_ItemCommand(object source, RepeaterCommandEventArgs e)
{
RepeaterItem item = e.Item;
TextBox Update_ID = (TextBox)item.FindControl("TextBoxUpdateID_Repeater");
try
{
conn5.Open();
using (SqlCommand cmd5 = new SqlCommand("SelectImages", conn5))
{
cmd5.CommandType = CommandType.StoredProcedure;
cmd5.Parameters.Add(new SqlParameter("#update_id", Update_ID.Text));
List<Images> Lst = new List<Images>();
using (SqlDataReader rdr5 = cmd5.ExecuteReader())
{
while (rdr5.Read())
{
Lst.Add(new Images { Image_ID = Convert.ToInt16(rdr5["Image_ID"]) });
}
if ((item.ItemType == ListItemType.Item) || (item.ItemType == ListItemType.AlternatingItem))
{
Repeater ImageRepeater = (Repeater)item.FindControl("RepeaterImages");
ImageRepeater.DataSource = Lst;
ImageRepeater.DataBind();
}
}
}
}
finally
{
conn5.Close();
}
}
HTML
You should Register ItemBoundData Event
<asp:Repeater ID="rp" runat="server" onitemdatabound="rp_ItemDataBound">
<ItemTemplate></ItemTemplate>
</asp:Repeater>
protected void rp_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
}
I have a repeater:
<asp:Repeater ID="rpt_Items" OnItemCommand="rpt_Items_ItemCommand" runat="server">
<ItemTemplate>
<div class="item">
<div class="fr">
<asp:TextBox ID="tb_amount" runat="server">1</asp:TextBox>
<p>
<%# Eval("itemPrice") %>
</p>
<asp:LinkButton ID="lb_buy" CommandName="buy" runat="server">buy</asp:LinkButton>
</div>
<asp:HiddenField ID="hdn_ID" Value='<%# Eval("itemID") %>' runat="server" />
</div>
</ItemTemplate>
</asp:Repeater>
On the repeater commandargument i want to get the textbox and the hiddenfield but how do i do this?
protected void rpt_Items_ItemCommand(object sender, RepeaterCommandEventArgs e)
{
if (e.CommandName == "buy")
{
//ADD ITEM TO CART
Response.Write("ADDED");
Product getProduct = db.Products.FirstOrDefault(p => p.ProductID == id);
if (getProduct != null)
{
CartProduct product = new CartProduct()
{
Name = getProduct.ProductName,
Number = amount,
CurrentPrice = getProduct.ProductPrice,
TotalPrice = amount * getProduct.ProductPrice,
};
cart.AddToCart(product);
}
}
}
Thanks a bunch!
You don't have to pass it through the Command Argument, you can use e.Item.FindControl() inside your rpt_Items_ItemCommand method, as in:
TextBox tb_amount = (TextBox)e.Item.FindControl("tb_amount");
HiddenField hdn_ID = (HiddenField)e.Item.FindControl("hdn_ID");