How to bind linq query to a repeater? - c#

I'm doing a search for name and surname via linq and I want to bind the results to a repeater.
What am I doing wrong?
// this the results for list
public static List<SearchResults> lsSearchResults = new List<SearchResults>();
public class SearchResults
{
public string Name { get; set; }
public string Surname { get; set; }
public SearchResults(string name, string surname)
{
Name = name;
Surname = surname;
}
}
// search button
protected void btnSearch_Click(object sender, EventArgs e)
{
var found = (from User in myDB.Memberships
where User.Name.ToLower().Contains(txtSearch.Text.ToLower()) ||
User.Surname.ToLower().Contains(txtSearch.Text.ToLower())
select new { User.Name, User.Surname });
// validates items in search query if Exist
if (!ChillZARdev.App_Code.Utilities.IsEmpty(found))
{
foreach (var user in found)
{
lsSearchResults.Add(new SearchResults(user.Name, user.Surname));
// ls.Add(user.Name + " " + user.Surname);
// Response.Write(user);
}
Repeater1.DataSource = lsSearchResults;
Repeater1.DataBind();
}
}
private bool IsEmpty(object found)
{
throw new NotImplementedException();
}
protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
WAT THE HELL I PUT IN HERE ?? LOL for this ish to work
CLUELESS
}
This is the HTML code of the repeater:
<asp:Repeater ID="Repeater1" runat="server" onitemdatabound="Repeater1_ItemDataBound">
<HeaderTemplate>
<table>
<tr>
<td>
<asp:Label ID="Label6" runat="server" Text='<%#Eval("Name")%>'></asp:Label>
<asp:Label ID="Label5" runat="server" Text='<%#Eval("Surname")%>'></asp:Label>
</td>
<td>
</td>
</tr>
</table>
</HeaderTemplate>
</asp:Repeater>

You just have to correct your Repeater declaration. After that there will be no need to handle ItemDataBound event at all:
<asp:Repeater ID="Repeater1" runat="server">
<HeaderTemplate>
<table>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td>
<asp:Label ID="Label6" runat="server" Text='<%#Eval("Name")%>'></asp:Label>
<asp:Label ID="Label5" runat="server" Text='<%#Eval("Surname")%>'></asp:Label>
</td>
<td>
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>

To get an object of your class back in the DataBound event, you just need to cast e.Item.DataItem to your class:
protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
var result = (SearchResult)e.Item.DataItem;
}
}

Related

Change repeater row value?

im trying to change a value inside my repeater : (via itemdatabound event)
if the year is empty - set value blabla
my repeater :
<ItemTemplate>
<tr >
<td >
<%#Eval("year") %>
</td>
my c# code :
void RPT_Bordereaux_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
if (string.IsNullOrEmpty(((DataRowView)e.Item.DataItem)["year"].ToString()))
{
(((DataRowView)e.Item.DataItem)["year"]) = "blabla"; // ???????
}
}
it does change but not displayed in repeater ( the old value is displayed).
one solution is to add a server control or literal ( runat server) in the itemTemplate - and to "findControl" in server - and change its value.
other solution is by jQuery - to search the empty last TD.
but - my question :
is there any other server side solution ( ) ?
you can try something like this :
Repeater in .aspx:
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<table>
<tr>
<td> <%# GetText(Container.DataItem) %></td>
</tr>
</table>
</ItemTemplate>
</asp:Repeater>
.cs :
protected static string GetText(object dataItem)
{
string year = Convert.ToString(DataBinder.Eval(dataItem, "year"));
if (!string.IsNullOrEmpty(year))
{
return year;
}
else
{
return "blahblah";
}
}
IN GetText Method you can able to check by string that Empty or not than return string.
You could try to use the itemcreated event which occurs before the control is bound and not after the control is bound. Example in first link:
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.repeater.itemcreated.aspx
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.repeater_events.aspx
ItemDataBound Occurs after an item in the Repeater control is data-bound but before it is rendered on the page.
HTML FILE
<asp:Repeater ID="RPT_Bordereaux" runat="server">
<ItemTemplate>
<table>
<tr>
<td> <%# GetValue(Container.DataItem) %></td>
</tr>
</table>
</ItemTemplate>
</asp:Repeater>
.CS CODE
protected void RPT_Bordereaux_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
}
}
protected static string GetValue(object dataItem)
{
string year = Convert.ToString(DataBinder.Eval(dataItem, "year"));
if (!string.IsNullOrEmpty(year))
{
return Convert.ToString(year);
}
else
{
return "blahbla";
}
}
This should work

ASP.NET - Nested Repeaters

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)
{
}

catching SelectedIndexChanged of a dropdown list inside a repeater

I am trying to catch the SelectedIndexChanged of a DropDownList inside a Repeater. I have searched the internet but could not find a specific answer any help would be great. This is my code.
page.aspx
<asp:Repeater id="CategoryMyC" OnItemCommand="SomeEvent_ItemCommand" runat="server">
<HeaderTemplate>
<table><tr>
</HeaderTemplate>
<ItemTemplate>
<td>
<table width="100%">
<tr>
<th>Edit Carousel Item</th>
</tr>
<tr>
<td>Choose a product:</td>
</tr>
<tr>
<td>
<asp:DropDownList ID="ddlMcProducts"
DataTextField="Name"
onselectedindexchanged="MyListIndexChanged"
AutoPostBack="true"
DataSource='<%# ProductsManager.GetMerchantProductRepeater(Convert.ToInt32(Eval("MID"))) %>'
runat="server">
</asp:DropDownList>
</td>
</tr>
</table>
</td>
</ItemTemplate>
<FooterTemplate>
</tr>
</table>
</FooterTemplate>
</asp:Repeater>
page.aspx.cs
In the Page_Load:
List<CarouselProducts> CP = CarouselProductsManager.GetCarouselItems(Convert.ToInt32(Session["Mid"]));
CategoryMyC.DataSource = CP;
CategoryMyC.ItemDataBound += new RepeaterItemEventHandler(RepeaterItemDataBound);
CategoryMyC.DataBind();
Other events:
protected void ddlMcProducts_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList d = (DropDownList)sender;
// Use d here
System.Windows.Forms.MessageBox.Show("I am changing");
}
protected virtual void PageInit(object sender, EventArgs e)
{
//get all the Carousel item of the merchant
List<CarouselProducts> CP = CarouselProductsManager.GetCarouselItems(Convert.ToInt32(Session["Mid"]));
//MerchantCategoryMyCarousel.DataSource = CP;
//MerchantCategoryMyCarousel.DataBind();
MerchantCategoryMyCarousel.DataSource = CP;
MerchantCategoryMyCarousel.ItemDataBound += new RepeaterItemEventHandler(RepeaterItemDataBound);
MerchantCategoryMyCarousel.DataBind();
}
protected virtual void RepeaterItemDataBound(object sender, RepeaterItemEventArgs e)
{
DropDownList theDropDown = sender as DropDownList;
if (e.Item.ItemType == ListItemType.EditItem)
{
DropDownList MyList = (DropDownList)e.Item.FindControl("ddlMcProducts");
if (MyList == null)
{
System.Windows.Forms.MessageBox.Show("Did not find the controle");
}
else
MyList.SelectedIndexChanged += new EventHandler(MyListIndexChanged);
}
}
protected virtual void MyListIndexChanged(object sender, EventArgs e)
{
System.Windows.Forms.MessageBox.Show("I am changing");
}
protected void SomeEvent_ItemCommand(object sender, RepeaterCommandEventArgs e)
{
if (e.CommandSource.GetType() == typeof(DropDownList))
{
DropDownList ddlSomething = (DropDownList)e.Item.FindControl("ddlSomething");
System.Windows.Forms.MessageBox.Show("I am changing");
//Now you can access your list that fired the event
//SomeStaticClass.Update(ddlSomething.SelectedIndex);
}
}
I need to catch the SelectedIndexChanged of the populated DropDownList for each one generated.
You've got quite a mismatch of code going on here - using System.Windows.Forms in an ASP.NET application is just one of the issues. You appear to be assigning event handlers in the code-behind and in the markup (nothing necessarily bad about that, but there's seems to be no rhyme or reason to how you're doing it).
You're Repeater's ItemCommand event is bound to a method that is looking for a DropDownList that has a different ID than the one in your markup.
If you're using the System.Windows.Forms.MessageBox to debug (ala old school JavaScript and other language "debugging" methods), save yourself a world-class headache (not to mention a lot of unnecessary code cleanup when you're done with development) and step through your code in the debugger.
I'm not sure how the page will render, but I don't think you're using the HeaderTemplate and FooterTemplate quite the way they're intended.
All that said, try something like this:
Markup (ASPX page):
<asp:Repeater id="CategoryMyC" OnItemCommand="CategoryMvC_ItemCommand" OnItemDataBound="CategoryMvC_ItemDataBound" runat="server">
<HeaderTemplate>
<table>
<tr>
<th>Edit Carousel Item</th>
</tr>
</table>
</HeaderTemplate>
<ItemTemplate>
<table width="100%">
<tr>
<td>Choose a product:</td>
</tr>
<tr>
<td>
<asp:DropDownList ID="ddlMcProducts"
DataTextField="Name"
OnSelectedIndexChanged="ddlMcProducts_SelectedIndexChanged"
AutoPostBack="true"
DataSource='<%# ProductsManager.GetMerchantProductRepeater(Convert.ToInt32(Eval("MID"))) %>'
runat="server">
</asp:DropDownList>
</td>
</tr>
</table>
</ItemTemplate>
</asp:Repeater>
Code Behind (APSX.CS)
protected void Page_Load(object sender, EventArgs e)
{
List<CarouselProducts> CP = CarouselProductsManager.GetCarouselItems(Convert.ToInt32(Session["Mid"]));
CategoryMyC.DataSource = CP;
//This can be assigned in the markup
//CategoryMyC.ItemDataBound += new RepeaterItemEventHandler(RepeaterItemDataBound);
CategoryMyC.DataBind();
}
protected void ddlMcProducts_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList d = (DropDownList)sender;
// Use d here
}
protected void CategoryMyC_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
DropDownList theDropDown = sender as DropDownList;
if (e.Item.ItemType == ListItemType.EditItem)
{
DropDownList MyList = (DropDownList)e.Item.FindControl("ddlMcProducts");
// This section is not needed for what you are doing with it:
// If the control is null, handle it as an error
// There's no need to give it an event handler if it does exist, because
// you already did so in the markup
//if (MyList == null)
//{
//System.Windows.Forms.MessageBox.Show("Did not find the controle");
//}
//else
//MyList.SelectedIndexChanged += new EventHandler(MyListIndexChanged);
//}
}
}
protected void CategoryMyC_ItemCommand(object sender, RepeaterCommandEventArgs e)
{
if (e.CommandSource.GetType() == typeof(DropDownList))
{
// Note the correct control name is being passed to FindControl
DropDownList ddlSomething = (DropDownList)e.Item.FindControl("ddlMcProducts");
//System.Windows.Forms.MessageBox.Show("I am changing");
//Now you can access your list that fired the event
//SomeStaticClass.Update(ddlMcProducts.SelectedIndex);
}
There may be more issues at hand as well - but this will hopefully streamline it enough for you to make some progress.
protected void drpOrganization_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList ddl = (DropDownList)sender;
RepeaterItem item = (RepeaterItem)ddl.NamingContainer;
if (item != null)
{
CheckBoxList list = (CheckBoxList)item.FindControl("chkSite");
if (list != null)
{
}
}
}

Edit Textbox in Repeater

I have a repeater with a textbox inside. I am trying to edit the information inside the textbox, retrieve the new data, and write to the DB. With my code its giving me the original info that was in the box. Not the new information that I have added. Here is my code
html:
<asp:LinkButton id="saveReviewLinkButton" text="Save" runat="server" onCommand="saveReviewLinkButton_OnCommand" />
<table>
<asp:Repeater id="ReviewRepeater" runat="server" onItemDataBound="ReviewRepeater_ItemDataBound">
<itemtemplate>
<tr >
<td ><asp:TextBox id="titleLabel" runat="server" width="200px" textMode="MultiLine"/></td>
</tr>
</itemtemplate>
</table>
c#:
protected void ReviewRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if ((e.Item.ItemType == ListItemType.Item) || (e.Item.ItemType == ListItemType.AlternatingItem))
{
Review review = (Review)e.Item.DataItem;
TextBox titleLabel = (TextBox)e.Item.FindControl("titleLabel");
titleLabel.Text = review.Title;
}
}
protected void saveReviewLinkButton_OnCommand(object sender, EventArgs e)
{
TextBox titleLabel = new TextBox();
foreach (RepeaterItem dataItem in ReviewRepeater.Items)
{
titleLabel = (TextBox)dataItem.FindControl("titleLabel");
string newInfo = titleLabel.Text;
}
}
Please make sure, you are binding the data to the repeater by checking in page load
if(!IsPostBack)
BindData();

Get selected dropdownlist value inside a repeater control

I have dropdownlist inside of a repeater control that I'm trying to get the value of and I'm getting "Object reference not set to an instance of an object". I am not sure what else to try. Thanks
ASPX CODE:
<asp:Repeater ID="GeneralRepeater" runat="server"
OnItemDataBound="GeneralRepeater_OnItemDataBound"
onitemcommand="GeneralRepeater_ItemCommand">
<HeaderTemplate></HeaderTemplate>
<ItemTemplate>
<tr>
<td class="style2">
</td>
<td class="style2">
<asp:DropDownList ID="GeneralDDL" AppendDataBoundItems="true" DataTextField="DiagnosisCode"
DataValueField="DiagnosisCode" runat="server" AutoPostBack="True" />
</td>
</tr>
</ItemTemplate>
<FooterTemplate></FooterTemplate>
</asp:Repeater>
</asp:Panel>
CODE BEHIND:
protected void GeneralRepeater_OnItemDataBound(object sender,
RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item ||
e.Item.ItemType == ListItemType.AlternatingItem)
{
DropDownList myDDL = (DropDownList)e.Item.FindControl("GeneralDDL");
Diagnosis oDiagnosis = new Diagnosis();
DataView dv = new DataView(oDiagnosis.GetDiagnosis());
myDDL.DataSource = dv;
myDDL.DataTextField = "DiagnosisCode";
myDDL.DataValueField = "DiagnosisCode";
myDDL.DataBind();
}
}
protected void cmdSave_Click(object sender, EventArgs e)
{
string ProductSelected;
string FeatureSelected;
string SectionSelected;
foreach(RepeaterItem dataItem in GeneralRepeater.Items)
{
ProductSelected = ((DropDownList)GeneralRepeater.FindControl("GeneralDDL")).SelectedItem.Text; //error Object reference not set to an instance of an object.
}
}
I having problem on Saving the selected value..
What i find in the code is you are looping through the generalrepeater items. You are accessing the repeater item as dataItem. I tried out this code out here and ideally your code should say
foreach(RepeaterItem dataItem in GeneralRepeater.Items)
{
ProductSelected = ((DropDownList)dataItem.FindControl("GeneralDDL")).SelectedItem.Text; //No error
}
instead of
foreach(RepeaterItem dataItem in GeneralRepeater.Items)
{
ProductSelected = ((DropDownList)GeneralRepeater.FindControl("GeneralDDL")).SelectedItem.Text; //error Object reference not set to an instance of an object.
}

Categories

Resources