Reputation: 2140
I am using a Repeater to get items from the database.
I place every item into the web user control page, with this code:
<%#DataBinder.Eval(Container.DataItem, "XXXX")%>
XXXX = attribute from the database, for example: Username.
In the .cs file of the web user control page, I want to get the ID(which is also in the database) from every single repeated element, any clue how I can do that?
For example:
The <%#DataBinder.Eval(Container.DataItem, "Username")%>
is showing the username of every person who is in the database. And in the .cs-file I want to get the ID of that username. So I can use a SQL-query like this when a button is clicked next to that repeated username:
UPDATE Table SET Username = "Mike" WHERE ID = '" + #### + "'
I don't know what to write in place of the ####.
This: #### = ID from the repeated Username where the button is clicked.
Thanks in advance!
Upvotes: 1
Views: 728
Reputation: 2738
With a Repeater, a good way is to use a command button.
In you .aspx, define a command button in the repeater ItemTemplate:
<asp:Repeater ID="repUsers" runat="server" OnItemCommand="repUsers_ItemCommand">
<ItemTemplate>
<asp:Button runat="server" CommandName="select" CommandArgument='<%#Eval("Id")%>' Text="Select" />
<span><%#Eval("Username")%></span>
<br />
</ItemTemplate>
</asp:Repeater>
In your .cs, capture the command button clicks:
protected void repUsers_ItemCommand(object source, RepeaterCommandEventArgs e)
{
if (e.CommandName == "select")
{
int userId = int.Parse(e.CommandArgument.ToString());
// do your db update here...
}
}
Upvotes: 1
Reputation: 5573
In your aspx page do the following:
<asp:Repeater OnItemCommand="ButtonCommandEvent" ID="myRepeater" runat="server">
<ItemTemplate>
...
<asp:HiddenField ID="recordId" runat="server" value='<%# Eval("id") %>' />
...
</ItemTemplate>
Then in your code behind you can wire your button to do the following:
void ButtonCommandEvent(Object obj, RepeaterCommandEventArgs e)
{
var temp = e.Item.FindControl("recordId") as HiddenField;
//use the value in temp to insert into your database
//UPDATE Table SET Username = "Mike" WHERE ID = temp
}
This will work as long as you have 1 button next to each repeated item.
Upvotes: 0