How to get data from controls in Repeater - asp.net

I have repeater with item template:
<asp:Repeater ID="queryParametersRepeater" runat="server"
DataSourceID="queryParametersObjectDataSource">
<ItemTemplate>
<tr class="itemTemplate">
<td class="labelTd" style="width: 300px;">
<asp:HiddenField runat="server" Value='<%# Eval("ParameterType") %>' />
Define <%# Eval("ParameterName") %> (type <%# Eval("ParameterType") %>)
</td>
<td class="valueTd">
<asp:TextBox runat="server" Width="300px" Text='<%# Eval("ParameterName") %>' />
<asp:CheckBox runat="server" Width="300px" />
</td>
</tr>
</ItemTemplate>
</asp:Repeater>
In jQuery I change display property of textBox and chekBox. How can I get data from those controls?
I can't use FindControls() function, because I don't know id of my controls.

You can use ID's and findcontrol to get the values. Here is a working example:
<%# Page Language="C#" %>
<%# Import Namespace="System.Collections.Generic" %>
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//bind the data source
RepeaterExample.DataSource = new List<KeyValuePair<int, string>>{
new KeyValuePair<int, string>(1, "Test1"),
new KeyValuePair<int, string>(2, "Test2"),
new KeyValuePair<int, string>(3, "Test3")
};
RepeaterExample.DataBind();
}
}
protected void cmdSubmit_Click(object sender, EventArgs e)
{
//read the values and output them
litResults.Text = "";
foreach (RepeaterItem i in RepeaterExample.Items)
{
TextBox txtExample = (TextBox)i.FindControl("txtExample");
if (txtExample != null)
{
litResults.Text += txtExample.Text + "<br />";
}
}
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Repeater ID="RepeaterExample" runat="server">
<HeaderTemplate>
test</HeaderTemplate>
<ItemTemplate>
<asp:TextBox ID="txtExample" runat="server" Text='<%#Eval("Value") %>'></asp:TextBox>
</ItemTemplate>
</asp:Repeater><br />
<asp:Button ID="cmdSubmit" runat="server" Text="Submit" OnClick="cmdSubmit_Click" />
<br />
<asp:Literal ID="litResults" runat="server"></asp:Literal>
</div>
</form>
</body>
</html>

Can you add a class to your controls?
If so you could try with $(".givenClass").

Related

get the value of all the checked checkboxes on button click

I have created a table in my .aspx file that looks like this:
Here is the code that does this:
<!-- code for generating the "add selected sessions" button -->
<table>
<tr>
<td><strong>Individual Sessions</strong></td>
<td >
<div class="addButton" style="text-align: center;">
<asp:LinkButton ID="LinkButton2" runat="server" Text="Add Selected Sessions" OnClick="btnAddToCart_Click" />
</div>
</td>
</tr>
</table>
<!-- add all the sessions for the user to select -->
<asp:Repeater ID="rptFeesSession" runat="server">
<HeaderTemplate>
<table >
</HeaderTemplate>
<ItemTemplate>
<asp:HiddenField ID="hdnIsSession" runat="server" Value='<%#Eval("isSession")%>' />
<tr runat="server" visible='<%# Eval("isSession")%>'>
<td valign="top" colspan="2" style="position: relative;">
<asp:HyperLink CssClass="siteColorFG popBtn" ID="hlFeeType" runat="server" Text='<%#Eval("title")%>' NavigateUrl="javascript:;"/>
</td>
<td valign="top">
<div class="">
<asp:CheckBox ID="LinkButton3" CommandArgument='<%#Eval("id")%>'CssClass="checkB" OnClick="btnAddToCart_Click" runat="server" Text='<%#Eval("amount", "{0:C}")%>' />
</div>
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
In my code behind file i want to capture all the checkboxes that have been checked and their respective CommandArgument values.
protected void btnAddToCart_Click(object sender, EventArgs e)
{
using (MyEntities db = new MyEntities())
{
//button was clicked. fetch all the check boxes from the rptFeesSession repeater into an int[]
}
}
There are several issues in your code (including conceptual / logic)
Item events in a Repeater should address item related things.
Click event handler has no access to CommandArgument attribute. Use Command instead.
Checkbox control doesn't support onclick event.
Checkbox events can run immediately only when there is AutoPostback="true".
If you want to refresh all repeater data on change of any checkbox then you can do something like this.
<asp:ScriptManager runat="server" ID="scriptMgr" /><%-- Strongly recommended --%>
<asp:UpdatePanel runat="server">
<ContentTemplate>
<asp:Repeater ID="rptFeesSession" runat="server">
<HeaderTemplate>
<table>
</HeaderTemplate>
<ItemTemplate>
<asp:HiddenField ID="hdnIsSession" runat="server" Value='<%#Eval("isSession")%>' />
<tr runat="server" visible='<%# Eval("isSession")%>'>
<td colspan="2" style="position: relative;">
<asp:HyperLink CssClass="siteColorFG popBtn" ID="hlFeeType" runat="server" Text='<%#Eval("title")%>' NavigateUrl="javascript:;" />
</td>
<td>
<div class="">
<asp:HiddenField runat="server" ID="hidID" Value='<%#Eval("id") %>' />
<asp:CheckBox ID="LinkButton3"
AutoPostBack="true" CssClass="checkB"
OnCheckedChanged="LinkButton3_CheckedChanged" runat="server"
Text='<%#Eval("amount", "{0:C}")%>' />
</div>
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
</ContentTemplate>
</asp:UpdatePanel>
//.cs
protected void LinkButton3_CheckedChanged(object sender, EventArgs e)
{
decimal total = 0;
using (MyEntities db = new MyEntities())
{
foreach (RepeaterItem item in rptFeesSession.Items)
{
var chk = item.FindControl("LinkButton3") as CheckBox;
if(chk!=null && chk.Checked){
string id = (item.FindControl("hidID") as HiddenField).Value;
total += decimal.Parse(chk.Text);
//do stuff
}
}
}
}

Update value in modalpop panel inside the updatePanel

Here I try to update the Label value base on click event of Linkbutton which is inside the repeater control. Scenario is When I click on Linkbutton same time Modal popup open and the Label text also change.
Below is my code.
<%# Page Language="C#" AutoEventWireup="true" CodeFile="ModalPopupUpdatePanel.aspx.cs"
Inherits="ModalPopupUpdatePanel" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajaxToolkit" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>ModalPopups and UpdatePanels</title>
<link rel="stylesheet" href="StyleSheet.css" />
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager runat="server" ID="scriptMgr1">
</asp:ScriptManager>
<div style="width: 300px; left: 100px">
<div >
<asp:Label ID="Label2" runat="server">Update Panel that contains a ModalPopup and its associated PopupPanel inside it</asp:Label>
<asp:UpdatePanel runat="server" ID="updatePanel2" UpdateMode="Conditional" ChildrenAsTriggers="false">
<ContentTemplate>
<br />
<asp:Repeater runat="server" ID="btnresr" DataSourceID="SqlDataSource1">
<ItemTemplate>
<asp:LinkButton runat="server" ID="text" OnClick="Button5_Click" Text=' <%# DataBinder.Eval(Container.DataItem, "AgentName")%>' BackColor="Red"></asp:LinkButton>
</ItemTemplate>
</asp:Repeater>
<asp:Button runat="server" ID="button2" Text="Launch Modal Popup2" style="display:none"/>
<ajaxToolkit:ModalPopupExtender runat="server" ID="modalPopupExtender2" TargetControlID="button2"
PopupControlID="modalPanel2" OkControlID="okBtn2" CancelControlID="cancelBtn2"
BackgroundCssClass="modalBackground">
</ajaxToolkit:ModalPopupExtender>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:PTBWConnectionString %>"
SelectCommand="SELECT [AgentName], [AgentID] FROM [AgentMaster]">
</asp:SqlDataSource>
<asp:Panel runat="server" ID="modalPanel2" BackColor="AliceBlue" Style="display: none">
<asp:UpdatePanel runat="server" ID="updatePanel4" UpdateMode="Conditional" ChildrenAsTriggers="true">
<ContentTemplate>
<asp:Label runat="server" ID="label5" ></asp:Label>
<asp:Button runat="server" ID="postbackBtn" Text="Click to Cause postback" OnClick="postbackBtn_Click" /><br />
<asp:Button runat="server" ID="cancelBtn2" Text="OK" />
<asp:LinkButton runat="server" ID="okBtn2" Text="Cancel" />
</ContentTemplate>
</asp:UpdatePanel>
</asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</div>
</form>
</body>
</html>
and Code behind
using System;
using System.Web.UI.WebControls;
public partial class ModalPopupUpdatePanel : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void updateLabel_Click(object sender, EventArgs e)
{
}
protected void postbackBtn_Click(object sender, EventArgs e)
{
label5.Text = "After Postback";
}
protected void Button5_Click(object sender, EventArgs e)
{
LinkButton l = (LinkButton)sender;
label5.Text = "This is before postback,saroop";
modalPopupExtender2.Show();
}
}
I am block here please help me..Is there any Jquery way then also please here me
That is because the lable5 is not avaiable like that, it is nested inside the RepeaterItem.
Can you try this.
LinkButton l = (LinkButton)sender;
RepeaterItem rpt = (RepeaterItem)l.Parent();
Label label5 = (Label)rpt.FindControl("label5");
label5.Text = "This is before postback,saroop";
modalPopupExtender2.Show();

General idea how to highlight the selected Parent item in a Menu (using ListView)

So I have a Hierarchical Datasource that contains the information for a menu... I databind it to a ListView and use CSS to format it into a menu.. everything is good.. Now the next step I can't seem to understand..
How do I highlight (set the class of the ) the menu item that was just selected.. They are just links .. Should I somehow identify the ID of what was clicked and then use that to somehow loop through..?
Here is what I got so far so any tips in the right direction are good.
<asp:ListView ID="lvMainOuter" runat="server">
<LayoutTemplate>
<ul id="menunav" runat="server">
<asp:PlaceHolder ID="itemPlaceHolder" runat="server" />
</ul>
</LayoutTemplate>
<ItemTemplate>
<li <%# (Container.DataItem as FigLeafMenuItem).ItemSelected == "true" ? #" class=""MainMenuSelected""" : #" class=""""" %>>
<asp:HyperLink ID="nodeLink" runat="server" Text='<%# (Container.DataItem as FigLeafMenuItem).Name %>' NavigateUrl='<%# (Container.DataItem as FigLeafMenuItem).Url %>' />
<asp:ListView ID="lvMainInner" DataSource="<%# (Container.DataItem as FigLeafMenuItem).Children %>" runat="server">
<LayoutTemplate>
<ul id="menunav" runat="server">
<asp:PlaceHolder ID="itemPlaceHolder" runat="server" />
</ul>
</LayoutTemplate>
<ItemTemplate>
<li>
<asp:HyperLink ID="nodeLink" runat="server" Text='<%# (Container.DataItem as FigLeafMenuItem).Name %>' NavigateUrl='<%# (Container.DataItem as FigLeafMenuItem).Url %>' />
</li>
</ItemTemplate>
</asp:ListView>
</li>
</ItemTemplate>
</asp:ListView>
public int SelectedMenuId { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
lvMainOuter.ItemDataBound += lvMainOuter_ItemDataBound;
lvMainOuter.DataSource = new FigLeafMenu().GetFigLeafTopMenu();
lvMainOuter.DataBind();
}
void lvMainOuter_ItemDataBound(object sender, ListViewItemEventArgs e)
{
if (e.Item.ItemType == ListViewItemType.DataItem)
{
ListViewDataItem dataItem = (ListViewDataItem)e.Item;
//WHAT DO I DO NOW TO GET THE SELECTED ITEM AND ASSIGN IT A CLASS?
}
}
Try this
<asp:ListView ID="lvMainInner" DataSource="<%# (Container.DataItem as FigLeafMenuItem).Children %>"
runat="server">
<LayoutTemplate>
<ul id="menunav" runat="server">
<asp:PlaceHolder ID="itemPlaceHolder" runat="server" />
</ul>
</LayoutTemplate>
<ItemTemplate>
<li>
<asp:HyperLink ID="nodeLink" runat="server" Text='<%# (Container.DataItem as FigLeafMenuItem).Name %>'
NavigateUrl='<%# (Container.DataItem as FigLeafMenuItem).Url %>' />
</li>
</ItemTemplate>
<SelectedItemTemplate>
<li>
<asp:HyperLink ID="nodeLink" CssClass="MyHighlightClass" runat="server" Text='<%# (Container.DataItem as FigLeafMenuItem).Name %>'
NavigateUrl='<%# (Container.DataItem as FigLeafMenuItem).Url %>' />
</li>
</SelectedItemTemplate>
</asp:ListView>
or you could use codebehind ...
lvMainInner.SelectedIndexChanged += (o, args) =>
{
//You can do whatever here
};
In your hyperlink markup you can set the CssClass to a conditional statement based on some statement right?

User control based on repeater

I develop user control based on repeater. It must contains predefined checkBox for each row.
Any suggestions?
Perhaps, something like this?
Default.aspx
<%# Page Language="C#" %>
<script runat="server">
protected override void CreateChildControls()
{
base.CreateChildControls();
LoadUserControl();
}
private void LoadUserControl()
{
ph.Controls.Clear();
Control c = LoadControl("~/WebUserControl.ascx");
c.ID = "foo";
ph.Controls.Add(c);
}
</script>
<html>
<body>
<form id="form1" runat="server">
<div>
<asp:PlaceHolder ID="ph" runat="server" />
</div>
<asp:Button runat="server" />
</form>
</body>
</html>
WebUserControl.ascx
<%# Control Language="C#" %>
<%# Import Namespace="System.Data" %>
<script runat="server">
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
if (!IsPostBack)
{
DataTable dt = GetRawDataTable();
dt.Rows.Add(dt.NewRow());
rpt.DataSource = dt;
rpt.DataBind();
}
}
private static DataTable GetRawDataTable()
{
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("product", typeof(string)));
dt.Columns.Add(new DataColumn("checked", typeof(bool), "false"));
return dt;
}
protected void OnBtnAddClicked(object sender, EventArgs e)
{
DataTable dt = GetRawDataTable();
foreach (RepeaterItem ri in rpt.Items)
{
TransferFromPage(ri, dt);
}
dt.Rows.Add(dt.NewRow());
rpt.DataSource = dt;
rpt.DataBind();
}
private static void TransferFromPage(RepeaterItem ri, DataTable dt)
{
DataRow row = dt.NewRow();
row["product"] = ((TextBox)ri.FindControl("txtProduct")).Text;
row["checked"] = ((CheckBox) ri.FindControl("chk")).Checked;
dt.Rows.Add(row);
}
protected void OnRptItemCmd(object sender, RepeaterCommandEventArgs ea)
{
switch (ea.CommandName)
{
case "RemoveRow":
DataTable dt = GetRawDataTable();
foreach (RepeaterItem ri in rpt.Items)
{
if (ri.ItemIndex == ea.Item.ItemIndex) continue;
TransferFromPage(ri, dt);
}
rpt.DataSource = dt;
rpt.DataBind();
break;
}
}
</script>
<div>
<table>
<asp:Repeater ID="rpt" runat="server" OnItemCommand="OnRptItemCmd">
<ItemTemplate>
<tr>
<td>
<asp:TextBox ID="txtProduct" runat="server" Text='<%# Eval("product") %>' />
<asp:CheckBox ID="chk" runat="server" Checked='<%# Eval("checked") %>' />
<asp:Button ID="btnRemove" runat="server" Text="-" CommandName="RemoveRow" />
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
<tr>
<td>
<asp:Button ID="btnAdd" runat="server" Text="+" OnClick="OnBtnAddClicked" />
</td>
</tr>
</FooterTemplate>
</asp:Repeater>
</table>
</div>
you can use the Repeater's ItemTemplate, to put necessary controls. Below is an example:
<asp: Repeater>
<ItemTemplate>
<asp:CheckBox ID="cbkWhatever" runat="server" Checked='<%# Eval("CbkDataField") %>' />
All other items for Repeater ...
</ItemTemplate>
</asp:Repeater>

ASP.NET treeview populate child nodes. How can I avoid a postback to server?

I am trying to test populate on demand for a treeview.
I follow the procedure from these links:
http://msdn.microsoft.com/en-us/library/e8z5184w.aspx
But the treeview still make a postback to the server if I expanded one of the tree nodes (If you put a breakpoint in the first line of Page_load event), thus refreshing the whole page. I am using VS2005 and Asp.net 2.0 (but the same issue occurs in VS2008)
My simple test page markup is:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="aspTreeview.aspx.cs" Inherits="aspTreeview" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td style="height: 80%; width: 45%;">
<asp:Panel ID="Panel1" runat="server" BorderColor="#0033CC" BorderStyle="Solid" ScrollBars="Both">
<asp:TreeView ID="TreeView1" runat="server" ShowLines="True" PopulateNodesFromClient="True" EnableClientScript="True" NodeWrap="True"
ontreenodepopulate="TreeView1_TreeNodePopulate" ExpandDepth="0">
</asp:TreeView>
</asp:Panel>
</td>
<td style="width: 10%; height: 80%;" >
<div>
<asp:Button ID="Button1" runat="server" Text="->" onclick="Button1_Click" />
</div>
<div>
<asp:Button ID="Button2" runat="server" Text="<-" />
</div>
</td>
<td style="width: 136px; height: 80%">
<asp:Panel ID="Panel2" runat="server" BorderColor="Lime" BorderStyle="Solid">
<asp:TreeView ID="TreeView2" runat="server" ShowLines="True" ExpandDepth="0">
</asp:TreeView>
</asp:Panel>
</td>
</tr>
<tr>
<td>
</td>
<td>
</td>
<td style="width: 136px">
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
The code behind is:
protected void Page_Load(object sender, EventArgs e)
{
Debug.WriteLine("Page_Load started.");
if (!IsPostBack)
{
if (Request.Browser.SupportsCallback)
Debug.WriteLine("Browser supports callback scripts.");
for (int i = 0; i < 3; i++)
{
TreeNode node = new TreeNode("ENTRY " + i.ToString());
node.Value = i.ToString();
node.PopulateOnDemand = true;
node.Expanded = false;
TreeView1.Nodes.Add(node);
}
}
Debug.WriteLine("Page_Load finished.");
}
protected void TreeView1_TreeNodePopulate(object sender, TreeNodeEventArgs e)
{
TreeNode targetNode = e.Node;
for (int j = 0; j < 4200; j++)
{
TreeNode subnode = new TreeNode(String.Format("Sub ENTRY {0} {1}", targetNode.Value, j));
subnode.PopulateOnDemand = true;
subnode.Expanded = false;
targetNode.ChildNodes.Add(subnode);
}
}
Page_Load is called but it's not a full postback in that the whole page doesn't have to be reloaded. See this answer for more information:
http://forums.asp.net/t/1024564.aspx/1
change runat="server" to runat="client"

Resources