Get checked checkbox list values inside a repeater - asp.net

How can I get checked values form checkboxlists inside a repeater, I have no idea how collect all checked values in a collection list.
<asp:Repeater runat="server" ID="rp_outer" OnItemDataBound="rp_outer_ItemDataBound">
<ItemTemplate>
<a class="collapsed btn" data-toggle="collapse" data-target="#Col<%#Eval("ProID") %>"> <%#Eval("PropEName") %></a>
<div id="Col<%#Eval("ProID") %>" class="collapse in">
<asp:CheckBoxList ID="cbxlist" runat="server" CssClass="filter-ul" DataSource='<%# DataBinder.Eval(Container.DataItem, "rltbls") %>' DataValueField='ID' DataTextField='ValuesEName'>
</asp:CheckBoxList>
</div>
<hr />
</ItemTemplate>
</asp:Repeater>

you need grouping items with ProId.
<ItemTemplate>
<a class="collapsed btn" data-toggle="collapse" data-target="#Col<%#Eval("ProID") %>"> <%#Eval("PropEName") %></a>
<asp:HiddenField runat="server" ID="ProID" Value="<%#Eval("ProID") %>"/>
<div id="Col<%#Eval("ProID") %>" class="collapse in">
....
You can create a dictionary list that uses ProId as a key
private Dictionary<string, List<string>> GetCheckedItems()
{
Dictionary<string, List<string>> checkedItemsList = new Dictionary<string, List<string>>();
foreach (RepeaterItem item in rp_outer.Items)
if (item.ItemType == ListItemType.Item)
{
CheckBoxList itemCheckBoxList = item.FindControl("cbxlist") as CheckBoxList;
if (itemCheckBoxList != null)
{
string proIdValue = (item.FindControl("ProID") as HiddenField).Value;
List<string> checkedItems = new List<string>();
foreach (ListItem checkBoxItem in itemCheckBoxList.Items)
if (checkBoxItem.Selected)
checkedItems.Add(checkBoxItem.Value);
checkedItemsList.Add(proIdValue, checkedItems);
}
}
return checkedItemsList;
}

Related

How to return parent field value to inner repeater?

I have below nested repeater, I need to return ID value from parent repeater then put it inside the Nested repeater.
ID_Parent=<% '?????? %> :
<asp:Repeater runat="server" ID="rp_outer">
<ItemTemplate>
<div id="<%#Eval("ID") %>">
<h4><%#Eval("Ename") %></h4>
<ul class="menu-items">
<asp:Repeater runat="server" ID="rp_inner_floorg" Visible="true"
DataSource='<%#(Container.DataItem).Row.GetChildRows("rltbls") %>'>
<ItemTemplate>
<li>
<a href='Products.aspx?ID_Parent=<% '?????? %>&InnerID=<%#CType(Container.DataItem, DataRow)("ID")%>'>
</a>
</li>
</ItemTemplate>
</asp:Repeater>
</ul>
</div>
</ItemTemplate>
</asp:Repeater>
**code-behind**
'Parrent
varSql = "SELECT ID,CatEname,HeadImg from qrywebsite_OuterMenue"
DataAdapter_1 = New SqlDataAdapter(varSql, varDbconn)
DataAdapter_1.Fill(ds, "tblCategory")
'Child
varSql = "select ID,Cat_Fkey,[SubCatEname] from qrywebsite_InnerSubCatMenu order by [Sequence]"
DataAdapter_2 = New SqlDataAdapter(varSql, varDbconn)
DataAdapter_2.Fill(ds, "tblSubCate")
ds.Relations.Add("rltbls", ds.Tables(0).Columns("ID"), ds.Tables(1).Columns("Cat_Fkey"), False)
ds.Relations("rltbls").Nested = true
rp_outer_catwgroy.DataSource = ds.Tables(0)
rp_outer_catwgroy.DataBind()
ds.Dispose()
DataAdapter_1.Dispose()
Replace ID_Parent=<% '?????? %> with:
<%# DataBinder.Eval(((RepeaterItem)Container.Parent.Parent).DataItem, "ID")%>

How to get the CommandArgument of an ImageButton inside a Repeater

I have a repeater which structured like this
<asp:Repeater ID="RpAccBind" runat="server" OnItemDataBound="RpAccBind_ItemDataBound">
<ItemTemplate>
<tr id="acsryRow" runat="server">
<td data-th="Product">
<div class="prodImgMain">
<img src="../instrumentimages/<%# Eval("ProductImage") %>" alt="<%# Eval("ProductName")%>" />
</div>
</td>
<td data-th="Description">
<div class="prodDescriptionContainer">
<ul>
<li>
<span class="prdRow"><%# Eval("ProductName") %></span>
</li>
</ul>
</div>
<div class="quantityIconWrap form-group">
<span class="number-wrapper">
<asp:TextBox Text='<%# Eval("Quantity") %>' ID="txtqty" CssClass="form-control" runat="server" size="3" Width="50" onkeyup="this.value=this.value.replace(/[^0-9]/g,'');" OnTextChanged="txtQtyTextChanged" AutoPostBack="true"></asp:TextBox>
</span>
<span>
<asp:ImageButton ID="lnkAscRemove" runat="server" class="btn" OnClick="lnkRemoveClick" CommandArgument='<%# Eval("ProductId")%>' ImageUrl="../images/deleteIcon.png"></asp:ImageButton>
</span>
</div>
</td>
<td data-th="Amount" style="padding-right: 5%;">
<div class="amountColMain">
<ul>
<li><span><strong><span id="litConPrice" runat="server">$<%# Eval("ConsumerPrice") %></span></strong></span></li>
</ul>
</div>
</td>
<td></td>
</tr>
</ItemTemplate>
<FooterTemplate>
</FooterTemplate>
</asp:Repeater>
Now, whenever the txtQty is 0, i want to have the productid in respect of the imagebutton clicked. Right Now, i am using something like
long productId = Convert.ToInt64(((ImageButton)((RepeaterItem)txtQty.Parent).FindControl("lnkAscRemove")).CommandArgument);
It is giving me an error of unable to cast HtmlTableCell to RepeaterItem
Any Kind of help will be appreciated. Thanks in advance
To use CommandName and CommandArgument, you need to use a Command event, not a Click.
<asp:ImageButton ID="lnkAscRemove" runat="server" OnCommand="lnkAscRemove_Command"
CommandArgument='<%# Eval("ProductId")%>'
Code behind
protected void lnkAscRemove_Command(object sender, CommandEventArgs e)
{
Label1.Text = e.CommandArgument.ToString();
}
Update
If you want to get the ProductId from a TextBox, you could add it as a custom property and then read it in code behind.
<asp:TextBox Text='<%# Eval("ProductId") %>' ID="txtqty" runat="server" AutoPostBack="true"
OnTextChanged="txtqty_TextChanged" ProductId='<%# Eval("ProductId") %>'></asp:TextBox>
Code behind
protected void txtqty_TextChanged(object sender, EventArgs e)
{
TextBox tb = sender as TextBox;
Label1.Text = tb.Attributes["ProductId"];
}
The Repeater has an ItemCommand that watches for button events inside the Repeater elements. The CommandName and CommandArgument is passed to the event.
Also of importance is the Item which represents the Repeater Item that the button was clicked in. Then you can use the FindControls method to find related server controls object for the same RepeaterItem in which the button was clicked.
protected void MyRepeater_ItemCommand(Object source, RepeaterCommandEventArgs e)
{
if (e.CommandName == "edit") {
SetEditorTo(e.CommandArgument);
}
RepeaterItem row = e.Item;
Textbox tQty = row.FindControls("txtqty");
}

TextBox inside a repeater control

I have a repeater control with an ItemTemplate containing two Textboxes. I loop through the Repeater and insert the data in my database. The problem is that the first TextBox is the only one inserted.
I bind the first TextBox in the List in the PageLoad method.
<asp:Repeater ID="questionRepeater" ViewStateMode="Enabled" runat="server">
<ItemTemplate>
<tr class="">
<td>
<div class="control-group">
<label class="control-label">Queston : </label>
<div class="controls">
<asp:TextBox runat="server" ID="txtQ" Text='<%#Eval("Question") %>' ReadOnly="true" CssClass="span8">
</asp:TextBox>
</div>
</div>
</td>
</tr>
<tr class="info">
<td>
<div class="control-group">
<label class="control-label">Answer : </label>
<div class="controls">
<asp:TextBox runat="server" ID="txtAns"
Height="150" TextMode="MultiLine" CssClass="span8"></asp:TextBox>
</div>
</div>
</td>
</tr>
</ItemTemplate>
</asp:Repeater>
My code behind:
protected void btnSave_Click(object sender, EventArgs e)
{
Sessions session = new Sessions();
SessionQuestion sessionQuestions = new SessionQuestion();
session.ClientId = id;
session.DateTime = DateTime.Now;
session.Report = txtReport.Text;
session.Notes = string.Empty;
session.IsActive = IsActive.Active;
int sessionId = SessionBLL.Insert(session);
foreach (Control item in questionRepeater.Items)
{
sessionQuestions.SessionId = sessionId;
TextBox txtQ = (TextBox)item.FindControl("txtQ");
sessionQuestions.Answer = "";
sessionQuestions.Question = txtQ.Text;
var txtAns = (TextBox)item.FindControl("txtAns") as TextBox;
if (txtAns != null)
{
sessionQuestions.Answer = "";
sessionQuestions.Answer = txtAns.Text;
}
Thread.Sleep(150);
if (txtAns != null && txtQ.Text != null)
{
SessionQuestionBLL.Insert(sessionQuestions);
}
}
string message = "";
Response.Redirect("/Sessions/Sessions.aspx?message=" + message);
}
Maybe that is because you did not enclose your repeater databinding in your Page_Load
If (!IsPostBack)
{
// Databind your repeater
}
Also, when you iterate through the repeater it is better to iterate through items of type item & alternative as shown below
foreach (RepeaterItem item in questionRepeater.Items)
{
if (item.ItemType == ListItemType.Item ||
item.ItemType == ListItemType.AlternatingItem)
{
}
}

Cannot access checkbox checkedchanged event inside DataList

I have checkboxes inside a datalist itemtemplate..But i cant access checkbox chechedchange event. I set AutoPostBack as true. But still cant fire event.
Here my codes.
<ul class="commentlist" >
<asp:DataList ID="datalistYorum" runat="server" DataSourceID="ods_yorumlar"
RepeatLayout="Flow" ItemStyle-Wrap="True" RepeatDirection="Horizontal"
onitemcreated="datalistYorum_ItemCreated"
onitemdatabound="datalistYorum_ItemDataBound" onload="datalistYorum_Load"
ondatabinding="datalistYorum_DataBinding">
<ItemTemplate>
<li class="comment">
<div class="comment-body">
<div class="comment-author vcard">
<div class="lightbox-photo">
<a class="image-overlay" href='<%# "Foto/profil/foto_buyuk/" + Eval("Yorum_Profil_Foto_Buyuk") %>' data-rel="prettyPhoto" title='<%# Eval("Yorum_UserName")%>'>
<img src='<%# "Foto/profil/foto_kucuk/" + Eval("Yorum_Profil_Foto_Kucuk") %>' alt='<%# Eval("Yorum_UserName")%>' class="avatar" />
</a>
</div>
<cite class="fn"><asp:HyperLink ID="linkProfil" runat="server" Text='<%# Eval("Yorum_UserName")%>' NavigateUrl='<%# "~/profil.aspx?user_id="+ Eval("User_ID") %>'></asp:HyperLink></cite>
<cite class="fn-time"><%# Eval("Yorum_Gecen_Zaman")%></cite>
</div>
<p><%# Eval("Yorum_Text")%></p>
<div class="reply"><asp:CheckBox ID="checkLike" runat="server" CssClass="comment-reply-link" AutoPostBack="True" />
<asp:ToggleButtonExtender ID="ToggleButtonLike" runat="server" TargetControlID ="checkLike" ImageHeight="32" ImageWidth="52" CheckedImageUrl="~/images/liked.png" UncheckedImageUrl="~/images/like.png" CheckedImageAlternateText="Like">
</asp:ToggleButtonExtender>
</div>
<div class="reply"><asp:CheckBox ID="checkDislike" runat="server" CssClass="comment-reply-link" AutoPostBack="True" />
<asp:ToggleButtonExtender ID="ToggleButtonDislike" runat="server" TargetControlID="checkDislike" ImageHeight="32" ImageWidth="62" UncheckedImageUrl="~/images/dislike.png" CheckedImageUrl="~/images/disliked.png">
</asp:ToggleButtonExtender>
</div>
</div>
</li>
</ItemTemplate>
</asp:DataList>
<asp:ObjectDataSource ID="ods_yorumlar" runat="server"
DataObjectTypeName="Yorum" TypeName="yonet" SelectMethod="PostYorumlariGetir"
ondatabinding="ods_yorumlar_DataBinding"
onselecting="ods_yorumlar_Selecting" onselected="ods_yorumlar_Selected">
<SelectParameters>
and code behind:
protected void datalistYorum_ItemDataBound(object sender, DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType==ListItemType.AlternatingItem)
{
CheckBox checkLike = (CheckBox)e.Item.FindControl("checkLike");
CheckBox checkDislike = (CheckBox)e.Item.FindControl("checkDislike");
if (!Page.IsPostBack)
{
checkLike.CheckedChanged += new EventHandler(checkLike_CheckedChanged);
checkDislike.CheckedChanged += new EventHandler(checkDislike_CheckedChanged);
}
}
}
public void checkLike_CheckedChanged(object sender, EventArgs e)
{
object user_id = Membership.GetUser().ProviderUserKey;
DateTime event_date = DateTime.Now;
CheckBox checkLike = (CheckBox)datalistYorum.FindControl("checkLike");
if (checkLike.Checked == true)
{
try
{
using (SqlConnection baglanti = new SqlConnection(ConfigurationManager.ConnectionStrings["xxx"].ConnectionString.ToString()))
{
SqlCommand komut = new SqlCommand("sp_likeordislike", baglanti);
komut.CommandType = CommandType.StoredProcedure;
komut.Parameters.AddWithValue("#comment",1);
komut.Parameters.AddWithValue("#user_id", user_id);
komut.Parameters.AddWithValue("#likeordislike", 1);
komut.Parameters.AddWithValue("#event_date", event_date);
baglanti.Open();
komut.ExecuteNonQuery();
baglanti.Close();
}
}
catch (Exception)
{
throw;
}
}
}
But nothing happen.Thanks!
Unless you are adding the event handler for the 'checklike' Checkbox in Page_Load it looks as though the assignment is missing.
Change the 'checklike' Checkbox declaration as follows:
<asp:CheckBox ID="checkLike" runat="server" CssClass="comment-reply-link" AutoPostBack="True" OnCheckedChanged="checkLike_CheckedChanged" />
Try this:
protected void checkDislike_CheckedChanged(Object sender, EventArgs e)
{
CheckBox cb = (CheckBox) sender;
DataListItem item = (DataListItem) cb.NamingContainer;
//
//
}
Your markup will look like this:
<asp:CheckBox ID="checkDislike" runat="server" CssClass="comment-reply-link" AutoPostBack="True" OnCheckedChanged="checkDislike_CheckedChanged" />
Before trying this comment out all the other checkbox events
Check this link:

Asp.Net binding specific fields of sql query to Listview

I have a listview that has a few different controls. I need to bind specific fields of a query to certain parts of a control. The table contains a friendid and a firstname. I want to put the friendid at the end of a URL. I want to put the firstname in the text of a label. There will be multiple friends returned on the query. The listview should show all in a separate row. Here is what I have, which is obviously not right.
<asp:ListView ID="lvFriends" runat="server">
<LayoutTemplate>
<ul ID="itemPlaceholderContainer" runat="server" style="">
<li ID="itemPlaceholder" runat="server" />
</ul>
</LayoutTemplate>
<ItemTemplate>
<li>
<div style="float:left;">
<a id="A1" href='<%# ResolveUrl(String.Format("~/UserPages/FriendsPages/FriendsProfile.aspx?friend={0}", Container.DataItem)) %>' runat="server"><asp:Image ID="ImageButton1" ImageUrl='<%# ResolveUrl(String.Format("~/UserPages/FriendsPages/FriendsThumbImage.aspx?friend={0}", Container.DataItem)) %>' runat="server" /></a>
</div>
<div style="margin-left:300px;">
<ul>
<li><asp:Label ID="FirstNameLabel" runat="server" Text='<%# Eval("FriendFN") %>' /></li>
</ul>
</div>
</li>
<div style="clear:both;"></div>
</ItemTemplate>
<ItemSeparatorTemplate><br /></ItemSeparatorTemplate>
</asp:ListView>
CODE BEHIND:
string strCon = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["SocialSiteConnectionString"].ConnectionString;
using (SqlConnection conn = new SqlConnection(strCon))
{
using (SqlCommand cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = "SELECT * from [Friends] WHERE [UserId] = #UserId";
cmd.Parameters.AddWithValue("#UserId", User.Identity.Name);
DataTable dtFriends = new DataTable();
dtFriends.Columns.Add("FriendId");
dtFriends.Columns.Add("FriendFN");
SqlDataReader nwReader = cmd.ExecuteReader();
while (nwReader.Read())
{
string RdFriendId = nwReader["FriendId"].ToString().ToLower();
string RdFriendFN = nwReader["FriendFirstName"].ToString().ToLower();
dtFriends.Rows.Add(new object[] {RdFriendId, RdFriendFN});
}
nwReader.Close();
Session.Add("FriendsTable", dtFriends);
conn.Close();
lvFriends.DataSource = dtFriends;
lvFriends.DataBind();
}
}
I would look into using a repeater control instead.

Resources