select index of listView is not working in ASP.NET - asp.net

I am new to ASP.NET, I am making a search box in my application.
For example: if a user enters "abc" in the textbox, then the textbox will fetch data from the database which starts with "abc". I am passing this data to DataTable.
It works properly,
Here is my code snippet:
DataTable result = new DataTable();
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
connString = System.Configuration.ConfigurationManager.ConnectionStrings["MyConsString"].ConnectionString;
SqlConnection conn = new SqlConnection(connString);
conn.Open();
string query = string.Format("SELECT DISTINCT Scrip FROM dbo.SearchBoxData where Scrip Like '{0}%'", TextBox1.Text);
SqlCommand cmd = new SqlCommand(query, conn);
result.Load(cmd.ExecuteReader());
conn.Close();
lvwItems.DataSource = result;
lvwItems.DataBind();
}
Now I want to retrieve all this data in my <div> tag. so i tried using asp:ListView,
here is my code snippet,
it works properly, but now i want to navigate to new page when user select any row of listView, but i am unable to select any row..
<asp:ListView ID="lvwItems" runat="server" ItemPlaceholderID="plhItems">
<LayoutTemplate>
<div>
<asp:PlaceHolder ID="plhItems" runat="server"></asp:PlaceHolder>
</div>
</LayoutTemplate>
<ItemTemplate>
<div>
<%# Eval("Scrip")%>
</div>
</ItemTemplate>
Thanks In Advance !!
Any help will be appreciated.
EDIT:(SearchBox.aspx.cs)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
public partial class SearchBox : System.Web.UI.Page
{
string connString;
DataTable result = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{ }
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
connString = System.Configuration.ConfigurationManager.ConnectionStrings["MyConsString"].ConnectionString;
SqlConnection conn = new SqlConnection(connString);
conn.Open();
string query = string.Format("SELECT DISTINCT Scrip FROM dbo.SearchBoxData where Scrip Like '{0}%'", TextBox1.Text);
SqlCommand cmd = new SqlCommand(query, conn);
result.Load(cmd.ExecuteReader());
conn.Close();
lvwItems.DataSource = result;
lvwItems.DataBind();
}
protected void lvwItems_SelectedIndexChanging(Object sender, ListViewSelectEventArgs e)
{
ListViewItem item = (ListViewItem)lvwItems.Items[e.NewSelectedIndex];
Label lablId = (Label)item.FindControl("lablId");
if (String.IsNullOrEmpty(lablId.Text))
{
Response.Redirect("NextPage.aspx?id=" + lablId.Text, false);
}
}
(SearchBox.aspx)
<%# Page Language="C#" AutoEventWireup="true" CodeFile="SearchBox.aspx.cs" Inherits="SearchBox" %>
<!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></title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
<asp:TextBox ID="TextBox1" runat="server" Height="30px" Width="179px"
OnTextChanged="TextBox1_TextChanged" AutoPostBack="true"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Go"
Width="62px" />
<asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>
<asp:ListView ID="lvwItems" OnSelectedIndexChanging="lvwItems_SelectedIndexChanging"
runat="server" ItemPlaceholderID="plhItems">
<LayoutTemplate>
<div>
<asp:PlaceHolder ID="plhItems" runat="server"></asp:PlaceHolder>
</div>
</LayoutTemplate>
<ItemTemplate>
<div>
<%# Eval("Scrip")%>
<asp:Label ID="lablId" visible="false" runat="server" Text='<%#Eval("Scrip") %>'/>
</div>
</ItemTemplate>
</asp:ListView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:krunal_DBConnectionString2 %>"
SelectCommand="SELECT * FROM [SearchBoxData]"></asp:SqlDataSource>
</form>
</body>
</html>

You have to add a SELECT button in the ItemTemplate, see the complete working code.
<asp:ListView ID="lvwItems" OnSelectedIndexChanging="lvwItems_SelectedIndexChanging"
runat="server" ItemPlaceholderID="plhItems">
<LayoutTemplate>
<div>
<asp:PlaceHolder ID="plhItems" runat="server"></asp:PlaceHolder>
</div>
</LayoutTemplate>
<ItemTemplate>
<%# Eval("Scrip")%>
<asp:LinkButton ID="SelectButton" runat="server" CommandName="Select" Text="Select" />
</ItemTemplate>
</asp:ListView>
protected void lvwItems_SelectedIndexChanging(Object sender, ListViewSelectEventArgs e)
{
ListViewItem item = (ListViewItem)lvwItems.Items[e.NewSelectedIndex];
Label lablId = (Label)item.FindControl("CONTROL_ID");
}
Thanks
Deepu

Probably you will have to add the event for Selected index change:
<asp:ListView ID="lvwItems" runat="server" ItemPlaceholderID="plhItems" OnSelectedIndexChanging="lvwItems_SelectedIndexChanging">

In code behind you can get the selected row item like below.
Also you can place a label or hidden field so that you can get some data from those control and pass it in to the next page.. (might be id or something).
<asp:ListView ID="lvwItems" OnSelectedIndexChanging="lvwItems_SelectedIndexChanging"
runat="server" ItemPlaceholderID="plhItems">
<LayoutTemplate>
<div>
<asp:PlaceHolder ID="plhItems" runat="server"></asp:PlaceHolder>
</div>
</LayoutTemplate>
<ItemTemplate>
<div>
<%# Eval("Scrip")%>
<asp:Label ID="lablId" visible="flase" runat="server" Text='<%#Eval("Id") %>' />
</div>
</ItemTemplate>
</asp:ListView>
void lvwItems_SelectedIndexChanging(Object sender, ListViewSelectEventArgs e)
{
ListViewItem item = (ListViewItem)lvwItems.Items[e.NewSelectedIndex];
Label lablId = (Label)item.FindControl("lablId");
if (String.IsNullOrEmpty(lablId.Text))
{
Response.Redirect("page.aspx?id="+lablId.Text,false);
}
}
Thanks
Deepu

Here you go,
Also remove the OnClick="callMethod" from the button. Since you have SelectedIndex method no need to have the onClick method.
protected void lvwItems_SelectedIndexChanging(Object sender, ListViewSelectEventArgs e)
{
ListViewItem item = (ListViewItem)lvwItems.Items[e.NewSelectedIndex];
Button btn = (Button)item.FindControl("btn1");
if(btn != null)
{
var buttonText = btn.Text;
}
}
Hope this helps
Thanks
Deepu

Related

Create a dropdown that filters the output of my repeater

I have a repeater that lists all the products in my Products table and I need a dropdown box to filter the repeater content by category_id. I have absolutely no idea what I'm doing. Here is my repeater:
<asp:Repeater ID="RShopItems" runat="server" ItemType="WebDevAssessment.Models.Product">
<ItemTemplate>
<div class="col-md-4 productOuterContainer">
<div class="col-md-10 col-md-offset-1 productInnerContainer border">
<a href='<%#"ProductDetails.aspx?item=" + Item.product_id %>' runat="server" target="_parent">
<img runat="server" alt='<%# Item.product_name %>' src='<%# Item.product_image1 %>'
style="width: 100%" class="img-thumbnail" />
</a>
<h4 class="text-center"><%# Item.product_name %></h4>
<p class="text-center">Size: <%#Item.product_size%> - $<%#Item.product_price%></p>
<p class="features_text text-center"><%#Item.product_feat_short%></p>
</div>
</div>
</ItemTemplate>
</asp:Repeater>
And the behind code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WebDevAssessment.Models;
namespace WebDevAssessment
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
using (WebDatabaseEntities wde = new WebDatabaseEntities())
{
var products = (from si in wde.Products
orderby si.product_price descending
select si).ToList();
// assign the data to the repeater
RShopItems.DataSource = products;
// trigger the repeater to incorporate to display the data
RShopItems.DataBind();
}
}
}
}
Ok, you can use this apporach.
In this example, we have a repeater - showing hotel names.
We have a drop down list to filter by city (no choice = all cities).
So, the mark up looks like this:
<asp:DropDownList ID="DropDownList1" runat="server" DataTextField="City" DataValueField="ID" AutoPostBack="True">
</asp:DropDownList>
<br />
<br />
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<div style="border-style:solid;color:black;width:250px;float:left">
<div style="padding:5px;text-align:right">
Hotel Name: <asp:TextBox ID="txtHotelName" runat="server" Text ='<%# Eval("HotelName") %>' Width="130px" />
<br />
First Name: <asp:TextBox ID="txtFirst" runat="server" Text ='<%# Eval("FirstName") %>' Width="130px" />
<br />
Last Name: <asp:TextBox ID="txtLast" runat="server" Text ='<%# Eval("LastName") %>' Width="130px" />
<br />
City: <asp:TextBox ID="txtCity" runat="server" Text ='<%# Eval("City") %>' Width="130px" />
<br />
</div>
</div>
</ItemTemplate>
</asp:Repeater>
And the code to load up drop, load up Repeater, and filter looks like this:
protected void Page_Load(object sender, System.EventArgs e)
{
if (IsPostBack == false)
{
LoadDropDown();
LoadGrid();
}
}
public void LoadDropDown()
{
// load drop down list
using (SqlCommand cmdSQL = new SqlCommand("SELECT ID, City from tblCity ORDER BY City",
new SqlConnection(My.Settings.TEST3)))
{
cmdSQL.Connection.Open();
DropDownList1.DataSource = cmdSQL.ExecuteReader;
DropDownList1.DataBind();
// add blank row choice to drop down list
DropDownList1.Items.Insert(0, new ListItem(string.Empty, string.Empty));
}
}
public void LoadGrid(string sFilter = "")
{
using (SqlCommand cmdSQL = new SqlCommand("SELECT * FROM tblHotels",
new SqlConnection(My.Settings.TEST3)))
{
if (sFilter != "")
{
cmdSQL.CommandText += " WHERE City = #City";
cmdSQL.Parameters.Add("#City", SqlDbType.NVarChar).Value = DropDownList1.SelectedItem.Text;
}
cmdSQL.CommandText += " ORDER BY HotelName";
cmdSQL.Connection.Open();
Repeater1.DataSource = cmdSQL.ExecuteReader;
Repeater1.DataBind();
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
LoadGrid(DropDownList1.SelectedItem.Text);
}
So it now looks like this:
So, on first load - you load up the dropdown, and the repeater.
Dropdown list has auto post back = true, and it simply filters the Repeater by applying a parameters (optional) to the data source for the repeater.
It not a lot of code, and I don't see any advantages to using linq as you are.

Take parameter from listview

i have this code:
protected void Button1_Click(object sender, EventArgs e)
{
System.Data.SqlClient.SqlConnection sc = new System.Data.SqlClient.SqlConnection(GetConnectionString());
{
System.Data.SqlClient.SqlCommand cmd;
sc.Open();
cmd = new System.Data.SqlClient.SqlCommand("SET IDENTITY_INSERT Zapas OFF INSERT INTO Zapas (Zapas.Sezona,.....)SELECT Zapas.Sezona,... FROM Zapas WHERE ID_zapas=#ID;", sc);
cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("#ID", System.Data.SqlDbType.Text)).Value = (TextBox)ListView1.FindControl("box1");
cmd.ExecuteNonQuery();
sc.Close();
Response.Redirect("~/Zapasy_seznam.aspx");
}
}
I need take value ID from listview, but with this code I have this error:
...expects the parameter '#ID', which was not supplied....
This part of my listview...
<asp:ListView ID="ListView1" runat="server" DataKeyNames="ID_zapas" DataSourceID="SqlDataSource1" style="text-align: center ">
<AlternatingItemTemplate>
<tr style="background-color: #e9ffe9;color: #284775;text-align:center">
<td>
<asp:TextBox ID="box1" runat="server" Text='<%# Eval("ID_zapas") %>' Visible="false" />
...
<td style="width:50px;background-color:white">
<asp:LinkButton ID="Button1" runat="server" OnClick="Button1_Click" Visible='<%# HttpContext.Current.User.IsInRole("admin") %>' CausesValidation="False" OnClientClick="javascript: return confirm('Opravdu chcete zápas zkopírovat?');">
<asp:Image ID="Image2" runat="server" ImageUrl="~/Icons/copy.png" Width="29px" Height="29px" ToolTip="Zkopírovat zápas" />
</asp:LinkButton>
</td>
</tr>
</AlternatingItemTemplate>
Have you some idea?
As per comments, please try this:
using System.Data.SqlClient;
protected void Button1_Click(object sender, EventArgs e)
{
var box1 = (TextBox)((LinkButton)sender).Parent.FindControl("box1");
using (var sc = new SqlConnection(GetConnectionString()))
{
using (var cmd = sc.CreateCommand())
{
sc.Open();
cmd.CommandText = "SET IDENTITY_INSERT Zapas OFF INSERT INTO Zapas (Zapas.Sezona,.....)SELECT Zapas.Sezona,... FROM Zapas WHERE ID_zapas=#ID;";
cmd.Parameters.AddWithValue("#ID", box1.Text);
cmd.ExecuteNonQuery();
sc.Close();
Response.Redirect("~/Zapasy_seznam.aspx");
}
}
}
When using data-aware controls such as a ListView here, the controls are created with automatic unique IDs per data item. This means that you can have more than 1 of the same control (such as "box1" in this case) within the page that should be referenced by the data item (((LinkButton)sender).Parent which is ListViewDataItem, representing the row).
ListViewDataItem.FindControl will find controls of a specific server ID within its own child scope, allowing you to get values for controls within the same row of the button that is being clicked.

display gridview data in another page or other gridview with row data in editable mode

I have a grid view with 10 columns when I click edit it need to display data in another page with the row data in editable mode and also some other columns of the tables. please help me out from this ...please...,
<pre>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
namespace WebApplication1
{
public partial class displaypage : System.Web.UI.Page
{
SqlConnection conn = new SqlConnection(#"Data Source=SRAVI-PC\SQLEXPRESS;Initial Catalog=testdb;Integrated Security=True");
protected void Page_Load(object sender, EventArgs e)
{
getdata();
}
public void getdata()
{
string cmd = "select * from namestb";
SqlDataAdapter da = new SqlDataAdapter(cmd, conn);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
}
protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
Response.Redirect("editpage.aspx");
}
}
} <code>
.aspx
<pre>
<%# Page Language="C#" AutoEventWireup="true" EnableEventValidation="false" CodeBehind="displaypage.aspx.cs" Inherits="WebApplication1.displaypage" %>
<!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></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ID="ImageButton1" runat="server" Height="30px"
ImageUrl="~/images/edit image.jpg" Width="38px"
onclick="ImageButton1_Click" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br />
<br />
</div>
</form>
</body>
</html>
<code>
You need to add RowCommand Event in GridView.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowCommand="GridView1_RowCommand">
<asp:LinkButton ID ="lnkEdit" runat ="server" CommandArgument='<%#Eval("Recordid")%>' CommandName ="cmdEdit" Text ='Edit'></asp:LinkButton>
</asp:GridView>
Here rocordid is the id of your record.
In Page behind you need to write code.
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "cmdEdit")
{
string Recordid = Convert.ToString(e.CommandArgument.ToString());
Response.Redirect("EditPage.aspx?recordid="+Recordid );
}
}
On EditPage you can get recordid from the query string and can fetch the record form the database for further processing.
I hope it will help you

Working with Datalist in asp.net?

good morning to all.
i place a datalist in my project in that i place a link button when i click on that link button a panel will open in that row with a textbox and a button. it is working fine but my problem is if i click on one link button of a row panel will open, when i click on second row link button the sencond row panel is opening but first row panel is not closing. I think you get my point owhter wise i will explain again this is my code check out
<form id="form1" runat="server">
<div>
<asp:DataList ID="Mydatalist" runat ="Server"
OnItemCommand="Mydatalist_ItemCommand" >
<ItemTemplate >
<table >
<tr>
<td>
<asp:Label ID="lblcouname" runat ="server"
Text ='<%# Eval("country_name") %>'></asp:Label>
</td>
<td>
<asp:LinkButton ID="lnkrepl" Text="reply"
CommandName ="reply" runat ="server"
CommandArgument ='<%# Eval("country_id") %>'>
</asp:LinkButton>
</td>
</tr>
</table>
<div>
<asp:Panel ID="mypane" runat ="Server" Visible ="false" >
<asp:TextBox ID="txtpane" runat ="Server" ></asp:TextBox><br />
<asp:Button ID="btnInsert" runat="Server" Text ="Insert" />
</asp:Panel>
</div>
</ItemTemplate>
</asp:DataList>
</div>
</form>
Code behind:
public partial class Datlist : System.Web.UI.Page
{
SqlConnection con; SqlDataAdapter da; DataSet ds;
protected void Page_Load(object sender, EventArgs e)
{
con = new SqlConnection(
#"server=msmsm;database=pop;user id=sa;password=abc");
con.Open();
if (!IsPostBack)
{
getCountry();
}
}
public void getCountry()
{
string sqr="select * from country";
da=new SqlDataAdapter (sqr,con);
ds = new DataSet();
da.Fill(ds,"country");
Mydatalist.DataSource = ds.Tables[0];
Mydatalist.DataBind();
}
protected void Mydatalist_ItemCommand(object source, DataListCommandEventArgs e)
{
Panel pn = (Panel)e.Item.FindControl("mypane");
pn.Visible = false;
if (e.CommandName == "reply")
{
pn.Visible = true;
}
}
}
You have to programmably hide it. THe DataList should have an items property, and as such you can loop through all items, find the panel control using FIndControl, and set its visibility to false.
EDIT: So you need to do:
private void HideItems()
{
foreach (var item in this.dl.Items)
{
var panel = item.FindControl("mypane") as Panel;
if (panel != null)
panel.Visible = false;
}
}
In ItemCommand, call this method to hide all the existing control's panels.

ASP.NET Change Dropdown Control ID Inside Repeater Item Dynamically

Can someone tell me how I can get this to work. I want to distinguish dropdown controls inside a repeater control. I understand now about the lifecyle and how the buffer is already writen, but what are my alternatives? Here is what happens
Code File
Dim repeatTimes((TotalAdInsured - 1)) As Integer
myRepeater.DataSource = repeatTimes
myRepeater.DataBind()
Aspfile
<asp:Repeater ID="myRepeater" runat="server">
<ItemTemplate>
<asp:DropDownList ID="AdTitle<%# Container.ItemIndex %>" runat="server">
<asp:ListItem Selected="True" Value="" Text=""/>
<asp:ListItem Selected="False" Value="Miss" Text="Miss"/>
<asp:ListItem Selected="False" Value="Ms" Text="Ms"/>
<asp:ListItem Selected="False" Value="Mrs" Text="Mrs"/>
<asp:ListItem Selected="False" Value="Mr" Text="Mr"/>
<asp:ListItem Selected="False" Value="Other" Text="Other"/>
</asp:DropDownList>
</ItemTemplate>
</asp:Repeater>
Returns this error
Parser Error Message: 'AdTitle<%# Container.ItemIndex %>' is not a valid identifier.
I want to distinguish dropdown
controls inside a repeater control.
You don't need to. Here's some sample code that might help you out:
Markup:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!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>
<asp:Label runat="server" ID="lblMsg" Text="Click a button" />
<hr />
<asp:Repeater runat="server" ID="rptAwesome" onitemcommand="rptAwesome_ItemCommand"
>
<ItemTemplate>
<asp:Button runat="server" ID="btnAwesome"
Text='<%# "Button #" + Container.ItemIndex %>'
CommandArgument='<%# Container.DataItem %>'/><br />
</ItemTemplate>
</asp:Repeater>
</div>
</form>
</body>
</html>
Codebehind:
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
var x = new int[] { 1, 2, 3, 4, 5 };
rptAwesome.DataSource = x;
rptAwesome.DataBind();
}
}
protected void rptAwesome_ItemCommand(object source, RepeaterCommandEventArgs e)
{
Button btnAwesome = (Button)e.CommandSource;
lblMsg.Text = string.Format("btnAwesome.ID = {0}, e.CommandArgument = {1}", btnAwesome.ID, e.CommandArgument);
}
}
You cannot create a Unique ID inside a repeater through the markup like that. You can however retrieve the dropdown in the codebehind by using FindControl on the Repeater.
Dim adTitle As DropDownList = MyRepeater.FindControl("AdTitle")
If (Not adTitle Is Nothing) Then
''Do something here
End If
Ok... in a nutshell you can't do what you're trying to do in the manner you are currently doing it.
The ID property of a control can only be set using the ID attribute in the tag and a simple value. Example: <asp:Button runat="server" id="Button1" />
I can see what your trying to do, but I don't really understand Why...
A repeater control will contain 1 item, per item in your datasource, so it's perfectly fine to just call your DropDownList ID="AdTitle" as that will be a different 'AdTitle' from the one in the next row.
To get them back server side, you would just iterate through the Items in your Repeater & FindControl("AdTitle") to get the specific DropDownList for that item.
If it's absolutely necessary to have the IDs incrementing, you'll need to do this programmatically (probably on the ItemDataBound event to create a DropDownList and add it to your ItemTemplate.
Expanding on BC's answer: I recently had the same issue, albeit with a checkbox, I needed to set the ID as I used that when persisting choices. A bit clunky but I did it when on Item Data Bound.
Here's the markup:
<asp:Repeater ID="Repeater1" runat="server" >
<HeaderTemplate>Header<br /><br /></HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="cb" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "Name") %>' />
...other controls removed for brevity
</ItemTemplate>
<FooterTemplate>
<asp:Button ID="Button1" runat="server" OnClick="Submit" Text="Submit" />
</FooterTemplate>
</asp:Repeater>
I set up and bound a collection of this class
public class mst
{
public int Id { get; set; }
public string Name { get; set; }
public string Number { get; set; }
public bool NumberRequired { get; set; }
}
Do the necessary in Page_Load
Repeater1.ItemDataBound += new RepeaterItemEventHandler(Repeater1_ItemDataBound);
Repeater1.DataSource = listOfMsts;
Repeater1.DataBind();
Followed by, this where I set ID:
void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
var mst = (mst)e.Item.DataItem;
((CheckBox)e.Item.FindControl("cb")).ID = mst.Id.ToString();
}
}
So when the submit button is hit I can loop thru and grab the Id of those checked and save:
protected void Submit(object sender, EventArgs e)
{
foreach (var item in Repeater1.Items)
{
var checkboxes = ((RepeaterItem)item).Controls.OfType<CheckBox>().ToList();
if (checkboxes[0].Checked)
{
Save(checkboxes[0].ID);
....other stuff
}
}
}
You could add an event handler to Repeater.ItemDataBound and create the control within the handler using the reference to the item container.

Resources