How to bind repeater in loop in c# - c#

I have used repeater in asp.net
<div class="slider-inner">
<div id="daslider" runat="server" class="da-slider">
<asp:Repeater ID="rptSlider" runat="server">
<ItemTemplate>
<asp:Panel ID="sld" runat="server" class="da-slide">
<h2><asp:Literal ID="lblTitle" runat="server"></asp:Literal></h2>
<p>
<asp:Literal ID="lblDescription" runat="server"></asp:Literal>
</p>
<div class="da-img">
<iframe id="framevid" runat="server" visible="false" width="530" height="300" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
<asp:Image ID="sldrimg" runat="server" CssClass="img-responsive"/>
</div>
</asp:Panel>
</ItemTemplate>
<FooterTemplate>
<asp:Panel ID="btnlinks" runat="server" class="da-arrows">
<span class="da-arrows-prev"></span>
<span class="da-arrows-next"></span>
</asp:Panel>
</FooterTemplate>
</asp:Repeater>
</div>
</div>
In CS File I want to bind them programically using loop as below lines of code
private void GetMainAppSettings()
{
MainSetting Item = context.FetchMainAppSettings();
SliderContext contextSlider = new SliderContext();
Slider SW = new Slider();
string PageName = "Home Page";
IEnumerable<_14Muslims.Domain.Entity.Slider> pType = contextSlider.SliderFetchAllEnabled(PageName);
foreach (Slider item in pType)
{
lblTitle.Text = item.SliderTitle;
lblDescription.Text = item.SliderDescription;
framevid.Attributes.Add("src", item.SliderImage);
sldr.Attributes.Add("src", item.SliderImage);
daslider.Style.Add("background-image", WebUtility.UrlSchemeAuthority() + #"/FileStore/AppSettingsSiteLogos/" + item.BackgroundImage);
}
}
Note that GetMainAppSettings() is called on page_load event
Please Help me !!!

There are two separate things that you need to do:
Set the source of the repeater
Tell the repeater what to do for each item in the source.
To achieve the first, you just need to set the DataSource property of the repeater to the collection of items you need displayed, and execute a DataBind call:
private void GetMainAppSettings()
{
MainSetting Item = context.FetchMainAppSettings();
SliderContext contextSlider = new SliderContext();
Slider SW = new Slider();
string PageName = "Home Page";
IEnumerable<_14Muslims.Domain.Entity.Slider> pType = contextSlider.SliderFetchAllEnabled(PageName);
rptSlider.DataSource(pType);
rptSlider.DataBind();
}
When this is done, the repeater will loop through each item, process it and, display whatever is needed. To customize this process, the repeated provides an ItemDataBound event where you can set how the template should look for a specific item:
protected void rptSlider_ItemDataBound(object sender, RepeaterItemEventArgs e) {
// This event is raised for the header, the footer, separators, and items.
// Execute the following logic for Items and Alternating Items.
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) {
//get the item from the event arguments
var item = (Slider)e.Item.DataItem;
//get the controls
var lblTitle = (Label)e.Item.FindControl("lblTitle");
var lblDescription= (Label)e.Item.FindControl("lblDescription");
var framevid= (HtmlGenericControl)e.Item.FindControl("framevid");
var sldr= (HtmlGenericControl)e.Item.FindControl("sldr");
//set the values
lblTitle.Text = item.SliderTitle;
lblDescription.Text = item.SliderDescription;
framevid.Attributes.Add("src", item.SliderImage);
sldr.Attributes.Add("src", item.SliderImage);
}
}
This will execute once for each item in the data source, and you have complete control over what goes where and how. The looping is done implicitly for you by the repeater itself.

No need to loop the data in your code behind, you can directly assign the DataSource and Repeater control will take care of rest.
In Code behind, you can programatically set the DataSource like this:-
rptSlider.DataSource = pType;
rptSlider.DataBind();
In your repeater control, you can put the Data Binder code nuggets to assign particular properties to control like this:-
<h2><asp:Literal ID="lblTitle" runat="server" Text='<%# SliderTitle%>'></asp:Literal></h2>
and so on..for other controls.

Why use loop for bind repeater? You can directly assign your object "pType" to repeater data source. Like
IEnumerable<_14Muslims.Domain.Entity.Slider> pType = contextSlider.SliderFetchAllEnabled(PageName);
rptSlider.DataSource=pType;
rptSlider.DataBind();
After you can access all your field in repeater on .aspx page.
More Details see below article:
http://www.c-sharpcorner.com/UploadFile/5089e0/how-to-use-repeater-control-in-Asp-Net/

Related

Image Id is not showing at back end in C#

I am using Repeater control and in it I have one Image tag having id as 'imgGallery'. but in code behind file, I cannot access it.
aspx
<div class="col-md-4 col-sm-12">
<div class="col-md-2">
<asp:Repeater ID="rptImage" runat="server">
<ItemTemplate>
<asp:Image ID="imgGallery" runat="server" />
</ItemTemplate>
</asp:Repeater>
</div>
</div>
aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
using (DBDataContext dt = new DBDataContext())
{
var frm = from i in dt.GalleryMasters
where i.CategoryId == 1
select i;
foreach (var item in frm)
{
Image img = (Image)rptImage.FindControl("imgGallery");
img.ImageUrl = item.Image;
((HtmlControl)(FindControl("ifrm"))).Attributes["src"] = item.Video;
}
}
}
If I use FindControl then var is null.
First you need to bind your repeater:
rptImage.DataSource = frm.ToList();
rptImage.DataBind();
In your view should be possible to do this:
<asp:Image ID="imgGallery" runat="server" ImageUrl='<%# Eval("Video") %>' />
In code behind, to get items in your repeater, you need to iterate throught his items. The single item contains your image control. This should work:
foreach (RepeaterItem item in rptImage.Items) {
Image img = (Image)item.FindControl("imgGallery");
// Some other code
}
If you want to bind image in Repeater control based on Database result then you can directly assign datasource to Repeater control instead of finding image control.
Also Repeater does not have any record then it will not find any control which is inside the repeater as there is not any row in repeater.

Change order of listview based on Control inside listviewitem

I'm trying to create a blog page using a ListView. I am creating a reply function which adds a other css style to the listview when the message contains a parentmessageid.
This is working. Now I need to change the order of the message so the reply message will be placed under the parentmessage. Below you will find my implementation:
Function for datasource to fill the Listview:
protected void LoadMessages(int userid)
{
Bericht berichten = new Bericht();
if (berichten.LaadBerichten(userid).Tables.Count > 0)
{
ListViewMessages.DataSource = berichten.LaadBerichten(userid);
ListViewMessages.DataBind();
}
}
Function to add css style on items where LabelMessageID contains a value:
protected void ListItemMessages_Load(object sender, EventArgs e)
{
HtmlGenericControl li = (HtmlGenericControl)sender;
ListViewItem container = (ListViewItem)li.NamingContainer;
Label LabelParentMessageID = (Label)container.FindControl("LabelParentMessageID");
if (LabelParentMessageID.Text != string.Empty)
{
li.Attributes.Add("class", "reply");
}
}
ASP.NET ListView Source:
<asp:ListView ID="ListViewMessages" runat="server">
<ItemTemplate>
<li id="ListItemMessages" runat="server" onload="ListItemMessages_Load">
<img src="<%# Eval("[imagelocation]")%>" alt="image" />
<div class="top-pointer"></div>
<div class="pointer"></div>
<!--Hidden Controls-->
<asp:Label ID="LabelMessageID" runat="server" Text='<%# Eval("[messageid]")%>' Visible="false"></asp:Label>
<asp:Label ID="LabelParentMessageID" runat="server" Text='<%# Eval("[parentmessageid]")%>' Visible="false"/>
</li>
</ItemTemplate>
</asp:ListView>
Can someone help me out with changing the order of the items? Because I have no idea how to accomplish this.
try something like ds.Tables[0].DefaultView.Sort = "SortField DESC";
Solved using a SQL stored procedure.

Asp.net repeater control with checkboxlist

Binding data to checkbox list inside a repeater controls ItemDataBound event.
Here is Aspx code:
<asp:Repeater ID="rptrSelectedRcds" runat="server">
<ItemTemplate>
<div id="groupsDiv" runat="server">
<div class="hidden" id="divGroupSelector" runat="server">
<asp:CheckBoxList runat="server" ID="chkLstGroups"
RepeatDirection="Vertical">
</asp:CheckBoxList>
</div>
<asp:Button ID="btnConfirmGroups" runat="server" Text="Confirm" />
</div>
</ItemTemplate>
</asp:Repeater>
Code used inside ItemDataBound to bind data to repeater control:
protected void rptrSelectedRcds_ItemDataBound(object sender, System.Web.UI.WebControls.RepeaterItemEventArgs e)
{
Int32 iProviderID = Convert.ToInt32(((Label)e.Item.FindControl("lblIndividualID")).Text);
HtmlGenericControl selectGroupsDiv = (HtmlGenericControl)e.Item.FindControl("divGroupSelector");
if (divGroupSelector != null)
{
CheckBoxList chkLstGroups = (CheckBoxList)e.Item.FindControl("chkLstGroups");
chkLstGroups.DataSource = GetStateGroupsByProvider(stateValue, iProviderID);
//This code line gives different values for each record
chkLstGroups.DataTextField = "Name";
chkLstGroups.DataValueField = "pkID";
chkLstGroups.DataBind();
}
}
I can see in firebug the ids for chkLstGroups are different, but values bind to it are same.I want different values for each different checkbox id generated as from method - GetStateGroupsByProvider
Please help me out..!
Thanks.!

How to Add UserControl Conditionally to Repeater Control?

I want to know how to Add a UserControl Conditionally to a Repeater Control. I have tried to add it to the placeholder which is in Repeater Control but unable to load the usercontrol. This following code doesn't work.
<asp:Repeater ID="ResultsRepeater" runat="server">
<HeaderTemplate></HeaderTemplate>
<ItemTemplate>
<div>
<asp:PlaceHolder ID="PlaceHolder1" runat="server">
</asp:PlaceHolder>
</div>
</ItemTemplate>
</asp:Repeater>
public void GetStatus(int i)
{
UserControl uc = new UserControl();
if(i==1)
{
uc = LoadControl("DraftList.ascx") as UserControl;
}
else if(i==2)
{
uc = LoadControl("FinalList.ascx") as UserControl;
}
PlaceHolder p1 = (PlaceHolder)ResultsRepeater.Items[0].FindControl("PlaceHolder1");
p1.Controls.Add(uc);
}
Is there some reason that you don't want to just handle all of this in the aspx? That would be the simplest and cleanest option:
<asp:Repeater runat="server" ID="ResultsRepeater">
<ItemTemplate>
<uc1:DraftList ID="DraftList1" runat="server" Visible='<%# ((int)Eval("Status") == 1)%>' />
<uc2:FinalList ID="FinalList1" runat="server" Visible='<%# ((int)Eval("Status") == 2)%>' />
</ItemTemplate>
</asp:Repeater>
If a control is not visible, (i.e., Visible=false) then no markup is rendered, so coding in this fashion would not create any more work for the server or the client browser, while having the benefit of being much easier to read and providing user control properties at design-time.
You would just need to make sure to register your controls at the top of the page:
<%# Register src="DraftList.ascx" tagname="DraftList" tagprefix="uc1" %>
<%# Register src="FinalList.ascx" tagname="FinalList" tagprefix="uc2" %>
Why don't you try adding it within the repeaters ItemDataBound event? I.e.,
<asp:Repeater ID="ResultsRepeater" OnItemDataBound="ResultsRepeater_ItemDataBound" runat="server">
<HeaderTemplate></HeaderTemplate>
<ItemTemplate>
<div>
<asp:PlaceHolder ID="PlaceHolder1" runat="server">
</asp:PlaceHolder>
</div>
</ItemTemplate>
</asp:Repeater>
and in the code behind
protected void ResultsRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
Panel PlaceHolder1 = (Panel)e.Item.FindControl("PlaceHolder1");
// declare/obtain the value of i given the DataItem
// e.g.,
int i = ((int)e.Item.DataItem); // or however you're getting i
if (i == 1)
{
var uc = LoadControl("~/DraftList.ascx");
PlaceHolder1.Controls.Add(uc);
}
else if (i == 2)
{
var uc = LoadControl("~/FinalList.ascx");
PlaceHolder1.Controls.Add(uc);
}
}
}
Judging by your last comment (to the question) you might need to also make sure you've attached and bound your datasource to the repeater as well. I.e.,
ResultsRepeater.DataSource = dataSource; //whatever your datasource is e.g., datatable, IEnumerable list etc
ResultsRepeater.DataBind();

Accessing Textboxes in Repeater Control

All the ways I can think to do this seem very hackish. What is the right way to do this, or at least most common?
I am retrieving a set of images from a LINQ-to-SQL query and databinding it and some other data to a repeater. I need to add a textbox to each item in the repeater that will let the user change the title of each image, very similar to Flickr.
How do I access the textboxes in the repeater control and know which image that textbox belongs to?
Here is what the repeater control would look like, with a submit button which would update all the image rows in Linq-to-SQL:
alt text http://casonclagg.com/layout.jpg
Edit:
This code works
Just make sure you don't blow your values away by Binding outside of if(!Page.IsPostBack) like me.. Oops.
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<div class="itemBox">
<div class="imgclass">
<a title='<%# Eval("Name") %>' href='<%# Eval("Path") %>' rel="gallery">
<img alt='<%# Eval("Name") %>' src='<%# Eval("Path") %>' width="260" />
</a>
</div>
<asp:TextBox ID="TextBox1" Width="230px" runat="server"></asp:TextBox>
</div>
</ItemTemplate>
</asp:Repeater>
And Submit Click:
protected void Button1_Click(object sender, EventArgs e)
{
foreach (RepeaterItem item in Repeater1.Items)
{
TextBox txtName = (TextBox)item.FindControl("TextBox1");
if (txtName != null)
{
string val = txtName.Text;
//do something with val
}
}
}
Have you tried something like following on the button click:-
foreach (RepeaterItem item in Repeater1.Items)
{
TextBox txtName= (TextBox)item.FindControl("txtName");
if(txtName!=null)
{
//do something with txtName.Text
}
Image img= (Image)item.FindControl("Img");
if(img!=null)
{
//do something with img
}
}
/* Where txtName and Img are the Ids of the textbox and the image controls respectively in the repeater.*/
Hope this helps.
.aspx
<asp:Repeater ID="rpt" runat="server" EnableViewState="False">
<ItemTemplate>
<asp:TextBox ID="txtQty" runat="server" />
</ItemTemplate>
</asp:Repeater>
.cs
foreach (RepeaterItem rptItem in rpt.Items)
{
TextBox txtQty = (TextBox)rptItem.FindControl("txtQty");
if (txtQty != null) { Response.Write(txtQty.Text); }
}
Be sure to add EnableViewState="False" to your repeater, otherwise you will get empty string. (That wasted my time, dont waste yours :) )
On postback, you can iterate over the collection of RepeaterItems in repeater.Items. You could then retrieve each TextBox with code such as
TextBox tbDemo = (TextBox)rptr.Items[index].FindControl("textBox");

Categories

Resources