How to get the value of a TextBox in an ASP.NET Repeater Control

By Peter Bromberg

The Repeater Control is a relatively simple ASP.NET control, but it can be used to display all kinds of tabular data via ItemTemplates and inserted markup. This explains how to click a button in a Repeater row and be able to get the value of a TextBox in that row. You can copy the code shown into an ASPX page and run it.

<%@ Page Language="C#" AutoEventWireup="true"  %>
<%@ Import Namespace="System.Data" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
protected void Page_Load (object sender, EventArgs e)
{
    if (!IsPostBack)
    {
       DataTable dt = new DataTable();
        dt.Columns.Add("ID");
        dt.Columns.Add("Firstname");
        dt.Columns.Add("Lastname");
        for (int i = 0; i < 10; i++)
        {
           DataRow row = dt.NewRow();
            row.ItemArray = new object[] {i,"Joe","Blow" +i.ToString( )};
             dt.Rows.Add(row);
            Repeater1.DataSource = dt;
            Repeater1.DataBind();
        }
     }
}

    protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
         int rowid = (e.Item.ItemIndex);
       TextBox tb = (TextBox)Repeater1.Items[rowid].FindControl("txtOne");
        Label2.Text = tb.Text;
    }
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Repeater Demo</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
<asp:Repeater ID="Repeater1" runat="server" onitemcommand="Repeater1_ItemCommand">
<HeaderTemplate>
<table border="1" width="50%">
<tr>
<th>SELECT</th>
<th>ID</th>
<th>FIRST</th>
<th>LAST</th>  
</tr>
</HeaderTemplate>

<ItemTemplate>
<tr>
  <td><asp:Button ID="btnOne" runat=server Text="SELECT"   /></td>
  <td> <asp:TextBox ID=txtOne runat=server Text='<%# Eval("ID") %>' /></td>
<td><%# Eval("Firstname") %></td>
<td><%# Eval("LastName") %></td>

</tr>
</ItemTemplate>

<FooterTemplate>
</table>
</FooterTemplate>
        </asp:Repeater>
    </div>
    <asp:Label ID=Label2 runat=server></asp:Label>
    </form>
</body>
</html>

How to get the value of a TextBox in an ASP.NET Repeater Control  (2681 Views)