TextBox inside a repeater control - asp.net

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

Related

How do I display child footer of a repeater if the child repeater is empty?

I have two repeaters nested in my application which is working fine. I would love to display the footer if the child repeater is empty. Due to my code my long html, i will just drop a sample of what my html looks like and post my full code for better understanding. Everything works fine though unless when the child repeater is empty i want to display the footer message
<asp:Repeater ID="ProductRepeater" runat="server" OnItemDataBound="ProductRepeater_ItemDataBound">
<HeaderTemplate></HeaderTemplate>
<ItemTemplate>
<table>
<tr>
<td>
<%#Eval("Name")%>
</td>
<tr>
</table>
<pre>
<asp:Repeater ID="ChildRepeater" runat="server">
<HeaderTemplate></HeaderTemplate>
<ItemTemplate>
<table>
<tr>
<td>
<%#Eval("Description")%>
<td>
</tr>
<table>
</itemTemplate>
<FooterTemplate>
<div>
<h5>
<asp:Label ID="lblDefaultMessage" runat="server" Text="This is empty. " Visible="false" ForeColor="Red" Font-Size="Large">
</asp:Label>
</h5>
</div>
</FooterTemplate>
</asp:Repeater>
</pre>
</ItemTemplate>
</asp:Repeater>
<protected void ProductRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if(e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
string category = "Value"
Repeater rptRelated = e.Item.FindControl("ChildRepeater") as Repeater;
rptRelated.DataSource = getChild(category);
rptRelated.DataBind();
if (rptRelated.Items.Count < 1)
{
if (e.Item.ItemType == ListItemType.Footer)
{
Label lblDefaultMessage = (Label)e.Item.FindControl("lblDefaultMessage");
lblDefaultMessage.Visible = true;
}
}
}
}
Repeater has no EmptyDataTemplate like GridView.
You should place your footer content next to Repeater and change your "databinding" code like this:
Repeater rptRelated = e.Item.FindControl("ChildRepeater") as Repeater;
Label lblDefaultMessage = (Label)e.Item.FindControl("lblDefaultMessage");
var ds = getChild(category);
lblDefaultMessage.Visible = ds != null && ds.Rows.Count != 0;
if (rptRelated != null)
{
rptRelated.DataSource = ds;
rptRelated.DataBind();
}
Find Repeater like:
// find Child Repeater
Control ctrl = (sender) as Control;
Repeater rptRelated = ctrl.Parent.NamingContainer as Repeater;
And Find control from Repeater's Footer like:
Label lblDefaultMessage =
(Label)rptRelated.Controls[rptRelated.Controls.Count-1].FindControl("lblDefaultMessage");
Add this into child Repeater's OnItemDataBound event instead of parent.
protected void ChildRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
Control ctrl = (sender) as Control;
Repeater rptRelated = ctrl.Parent.NamingContainer as Repeater;
if (rptRelated.Items.Count < 1)
{
if (e.Item.ItemType == ListItemType.Footer)
{
Label lblDefaultMessage = (Label)rptRelated.Controls[rptRelated.Controls.Count-1].FindControl("lblDefaultMessage");
lblDefaultMessage.Visible = true;
}
}
}
Event is:
<asp:Repeater ID="ChildRepeater" runat="server"
OnItemDataBound="ChildRepeater_ItemDataBound">

Nested ListView DataPager stops working with updatepanel

Here is my scenario:
I have several deals, each has a category, all are grouped by categories as such:
DealView: Name (the category), Deals (List of Deals objects)
the DealViews (List) is bound to the category list view, the listview on item databound generates the corresponding inner listviews and sets their corresponding data pagers paging size,it also decides whether to show the inner pagers or not. The OnLoad event of the categories listview is used for the postback of the any of the internal pagers. I can debug the code and i can see that the Load event is executed, the inner pagers SetPageProperties are also set correctly however nothing changes on the UI no matter how many times I click. If I remove the updatepanel, everything works as expected. Here is some, or alot of code :)
<div class="tabs-content">
<asp:UpdatePanel ID="upDeals" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:ListView ID="lvCategorisedDeals" runat="server" DataKeyNames="Deals" >
<LayoutTemplate>
<asp:PlaceHolder ID="itemPlaceholder" runat="server"></asp:PlaceHolder>
<div class="clear"></div>
</LayoutTemplate>
<ItemTemplate>
<div class="tab-item">
<asp:ListView runat="server" ID="lvCategoryDeals">
<LayoutTemplate>
<div class="deals">
<asp:PlaceHolder ID="itemPlaceholder" runat="server"></asp:PlaceHolder>
</div>
<div class="clear"></div>
</LayoutTemplate>
<ItemTemplate>
<div class="rc-item">
<h3><%# Eval("Title") %></h3>
<div class="deal-img">
<img src="<%# Eval("ImageUrl") %>" width="168" height="113">
</div>
<div class="deal-data">
<div class="info"><%# Eval("Caption") %></div>
<div class="price"><%# Eval("Currency") %> <%# Eval("DiscountedPrice") %></div>
<div class="deal-booking">Buy Now</div>
</div>
</div>
</ItemTemplate>
</asp:ListView>
<div class="dealsPager">
<asp:DataPager runat="server" ID="pgInner" PagedControlID="lvCategoryDeals" >
<Fields>
<asp:NumericPagerField />
</Fields>
</asp:DataPager>
</div>
</div>
</ItemTemplate>
</asp:ListView>
</ContentTemplate>
</asp:UpdatePanel>
</div>
And in the code behind:
void lvCategorisedDeals_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
foreach (var item in lvCategorisedDeals.Items)
{
if (item.ItemType == ListViewItemType.DataItem)
{
var lvInner = item.FindControl("lvCategoryDeals") as ListView;
if (lvInner == null)
throw new InvalidOperationException("The inner ListView was not found");
var pgInner = item.FindControl("pgInner") as DataPager;
if (pgInner == null)
throw new InvalidOperationException("The inner pager was not found");
if (lvCategorisedDeals.DataKeys == null && lvCategorisedDeals.DataKeys.Count == 0)
throw new InvalidOperationException("The outer ListViews Datakeys do not seem to be set");
var dataItem = lvCategorisedDeals.DataKeys[item.DisplayIndex].Value as List<GRCDeal>;
lvInner.PagePropertiesChanging += new EventHandler<PagePropertiesChangingEventArgs>(
(s, evt) =>
{
pgInner.SetPageProperties(evt.StartRowIndex, evt.MaximumRows, false);
// Get the data for the ListView lvInner
lvInner.DataSource = dataItem;
lvInner.DataBind();
}
);
}
}
}
}
void lvCategorisedDeals_ItemDataBound(object sender, ListViewItemEventArgs e)
{
var listViewDataItem = e.Item as ListViewDataItem;
if (listViewDataItem == null)
return;
if (listViewDataItem.ItemType == ListViewItemType.DataItem)
{
var lvInner = e.Item.FindControl("lvCategoryDeals") as ListView;
if (lvInner == null)
throw new InvalidOperationException("The inner ListView was not found");
var pgInner = e.Item.FindControl("pgInner") as DataPager;
if (pgInner == null)
throw new InvalidOperationException("The inner pager was not found");
var dataItem = listViewDataItem.DataItem as DealView;
pgInner.PageSize = this.PageSize;
pgInner.Visible = dataItem.Deals.Count > this.PageSize;
lvInner.DataSource = dataItem.Deals;
lvInner.DataBind();
}
Additional things to note is that I am passing that List of Deals as DataKeys and I am able to grab it fine. First binding happens on page load. The code is inside a user control part of Visual WebPart (SharePoint 2013).
Appreciate any help since this is killing me.

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:

Repeater inside repeater not binding properly

I have a repeater inside another. Like so :
<asp:Repeater ID="CategoryRepeater" runat="server" OnItemDataBound="ItemBound">
<ItemTemplate>
<div class="groupbox">
<fieldset>
<legend><%# Container.DataItem %></legend>
<table>
<asp:Repeater ID="ItemRepeater" runat="server">
<ItemTemplate>
<tr>
<td>
<asp:CheckBox id="chkItem" runat="server" Text='<%# Eval("Text")%>' />
<asp:Button ID="btnXRefs" Text="x-refs" runat="server" CssClass="xRefButton" OnClick="btnSelectXRefs_Click" />
</td>
</tr>
</ItemTemplate>
</asp:Repeater>
</table>
</fieldset>
</div>
</ItemTemplate>
</asp:Repeater>
CODE BEHIND :
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
using (var db = new DbContext())
{
CategoryRepeater.DataSource = db.Categories.OrderBy(x => x.Heading).Select(x => x.Heading).Distinct();
CategoryRepeater.DataBind();
}
}
}
protected void ItemBound(object sender, RepeaterItemEventArgs args)
{
if (args.Item.ItemType == ListItemType.Item)
{
Repeater childRepeater = (Repeater)args.Item.FindControl("ItemRepeater");
var item = args.Item as RepeaterItem;
using (var db = new DbContext())
{
childRepeater.DataSource = db.Categories.Where(x => x.Heading == item.DataItem).OrderBy(x => x.Text);
childRepeater.DataBind();
}
}
}
My goal is to first make many groupboxes using the top level, then bind items into each one. So I end up with many small stacked lists of checkboxes.
Problem is, all the top level boxes appear, yet only the first one contains checkbox items, ie. only the first one is bound internally, and the ItemBound method is only called once for the first one.
Any ideas why?
This line
if (args.Item.ItemType == ListItemType.Item)
Should be like this
if(args.Item.ItemType = ListItemType.Item ||
args.Item.ItemType == ListItemType.AlternatingItem)

ASP.Net dropdown always return first value on button click event

I am trying to save value from a simple asp.net form.
I have few controls on the page like drop-down & text-box's
I fill the first drop-down on page load with Language & trigger post-bask on same to fill the second drop-down ddCategoryType which it fills with correct values based on the language selected, but problem is when i try to get the value on button click event value for ddCategoryType.SelectedItem.Value always return 0 for some reason which i am not able figure out right now
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ddSelectLanguage.Items.Clear();
ddSelectLanguage.DataSource = DataProvider.GetLanguages();
ddSelectLanguage.DataBind();
ddSelectLanguage.Items.Insert(0, new ListItem("Select Language", "0"));
}
else
{
ddCategoryType.Items.Clear();
String strSql = "SELECT TypeName, TypeID FROM CategoryType WHERE LangID =" + ddSelectLanguage.SelectedItem.Value.ToString();
DataSet ds = new DataSet();
ds = DataProvider.Connect_Select(strSql);
ddCategoryType.DataSource = ds;
ddCategoryType.DataBind();
ddCategoryType.Items.Insert(0, new ListItem("Select Type", "0"));
}
}
protected void btnSaveCategory_Click(object sender, EventArgs e)
{
objArtCat.LanguageID = int.Parse(ddSelectLanguage.SelectedItem.Value.ToString());
objArtCat.CategoryName = txtCategoryName.Text;
objArtCat.CategoryType = int.Parse(ddCategoryType.SelectedItem.Value.ToString());
objArtCat.CategoryActive = bool.Parse(ddCategoryActive.SelectedItem.Value.ToString());
try
{
//bool result;
//result = objBLAddArticleCategory.CreateNewArticleCategory(objArtCat);
//if (result == true)
//{
// Response.Redirect("PageMessage.aspx?msg='Category has been Create Successfully'", true);
//}
//else
//{
//}
}
catch (Exception)
{ }
}
SAMPLE .ASPX CODE
<div class="row"></div>
<div class="row">
<asp:Label ID="lblSelectLang" CssClass="txtLabel" Text="Select Language :" runat="server" ></asp:Label>
<asp:DropDownList ID="ddSelectLanguage" runat="server" CssClass="ddGeneral"
DataTextField="LangName" DataValueField="LangID" CausesValidation="True"
AutoPostBack="True" >
</asp:DropDownList>
<asp:RequiredFieldValidator ID="rfvddLanguage" runat="server" ErrorMessage="Please Select Language" ControlToValidate="ddSelectLanguage"
InitialValue="Select Language" ValidationGroup="atpAddNewArticle" ></asp:RequiredFieldValidator>
</div>
<div class="row">
<asp:Label ID="lblCategoryName" CssClass="txtLabel" runat="server" Text="Category Name :"></asp:Label>
<asp:TextBox ID="txtCategoryName" runat="server" CssClass="txtbox300"></asp:TextBox>
<asp:RequiredFieldValidator ID="RFVtxtAuthorName" runat="server" ErrorMessage="*"
ControlToValidate="txtCategoryName" ValidationGroup="atpAddNewArticle" CssClass="validation"></asp:RequiredFieldValidator>
</div>
<div class="row">
<asp:Label ID="lblCategoryType" CssClass="txtLabel" runat="server" Text="Category Type :"></asp:Label>
<asp:DropDownList ID="ddCategoryType" runat="server" CssClass="ddGeneral" DataTextField="TypeName" DataValueField="TypeID" >
</asp:DropDownList>
</div>
<div class="row">
<asp:Label ID="lblCategoryActive" CssClass="txtLabel" runat="server" Text="Category Active :"></asp:Label>
<asp:DropDownList ID="ddCategoryActive" runat="server" CssClass="ddGeneral" >
<asp:ListItem Value="False" Selected="True">NO</asp:ListItem>
<asp:ListItem Value="True">YES</asp:ListItem>
</asp:DropDownList>
</div>
<div class="rowButton">
</br>
<asp:Button ID="btnUpdateArticle" runat="server" Text="Save Category" CssClass="btn" ValidationGroup="atpAddNewArticle" onclick="btnSaveCategory_Click" /> <input id="Reset" type="reset" class="btn" value="Reset" />
</div>
OutPut for ddCategoryType after postback
<div class="row">
<span class="txtLabel" id="MainContent_lblCategoryType">Category Type :</span>
<select class="ddGeneral" id="MainContent_ddCategoryType" name="ctl00$MainContent$ddCategoryType">
<option value="0" selected="selected">Select Type</option>
<option value="1">Article</option>
<option value="2">News</option>
<option value="3">Sports</option>
<option value="4">People</option>
<option value="5">Message</option>
</select>
</div>
In your Page_Load you are clearing the contents of ddCategoryType and therefore the SelectedIndex is reset to 0.
Remember that the Page_Load is always called, and it happens BEFORE the Button_Click event.
There are a few ways to handle this, for instance: don't perform all the code in your Page_Load's else clause if the SelectedIndex >= 0
Since you want to populate ddCategoryType based on a selected value from ddSelectLanguage, then populate the DDL based on that interaction, not in the Page_Load.
protected void Page_Load(object sender, EventArgs e)
{
ddSelectLanguage.SelectedIndexChanged += new
EventHandler(ddSelectLanguage_SelectedIndexChanged);
if (!IsPostBack)
{
ddSelectLanguage.Items.Clear();
ddSelectLanguage.DataSource = DataProvider.GetLanguages();
ddSelectLanguage.DataBind();
ddSelectLanguage.Items.Insert(0, new ListItem("Select Language", "0"));
}
}
Then
void ddSelectLanguage_SelectedIndexChanged(object sender, EventArgs e)
{
ddCategoryType.Items.Clear();
String strSql = "SELECT TypeName, TypeID FROM CategoryType WHERE LangID =" + ddSelectLanguage.SelectedItem.Value.ToString();
DataSet ds = new DataSet();
ds = DataProvider.Connect_Select(strSql);
ddCategoryType.DataSource = ds;
ddCategoryType.DataBind();
ddCategoryType.Items.Insert(0, new ListItem("Select Type", "0"));
}
also, make your query take parameters.

Resources