Reputation: 1038
I'm trying to populate a table using a database. I've been trying to follow numerous examples but to no avail. I feel like I'm missing something fundamental as this should be this hard... Thanks.
<table>
<asp:Repeater ID="rpt" runat="server">
<HeaderTemplate>
<tr>
<th></th>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td>
<asp:Label ID="data" runat="server" Text='<%= string.Format("{0}", My_Variable) %>' />
</td>
</tr>
</ItemTemplate>
</asp:Repeater>
</table>
C#
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection Conn = new SqlConnection(ConfigurationManager.ConnectionStrings["_connectionString"].ConnectionString);
SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM Customer", Conn);
DataTable table = new DataTable();
adapter.Fill(table);
rpt.DataSource = table;
rpt.DataBind();
}
private void rpt_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
//if (e.Item.ItemType ==
Label l = (Label)e.Item.FindControl("data");
l.Text = e.Item.DataItem.ToString();
}
Upvotes: 1
Views: 3955
Reputation: 1857
You could also use a simple BoundField as shown below...instead of a Label... (unless you need a label for any particular reason)...
<asp:BoundField HeaderText="Your Column Name"
DataField="YourDataTableColumnName"/>
You can also do formatting using the "DataFormatString" attribute of a BoundField.
Hope this helps...
Upvotes: 1
Reputation: 203829
Looks like you're most of the way there. e.Item.DataItem
is a DataRow (Since you bound a DataTable, which is just a bunch of DataRow
s. You'll want to cast that to a DataRow so that you can get stuff out of it. Next, you'll want to get at some column, i.e.
l.Text =((DataRow)e.Item.DataItem)["someColumn"];
The other option would be to just do the whole thing in markup, which would be easiest if you're just taking a value from the dataTable and putting it in a label's text, but you may need to use the databound event if it's harder.
<asp:Label ID="data" runat="server" Text='<%#Eval("MyColumnName")' />
Upvotes: 2
Reputation: 6995
You shouldn't need the rpt_ItemDataBound for most simple variables. In your .aspx file, try the Eval()
function instead:
<ItemTemplate>
<tr>
<td>
<asp:Label ID="data" runat="server" Text='<%#Eval("MyColumnName") %>' />
</td>
</tr>
</ItemTemplate>
Eval()
only works in the context of templated, databound controls. It takes the data source you specfied, finds the item currently being rendered by the repeater, and lets you access member properties on that item.
You only need to use the ItemDataBound
event when you need to render extra stuff that isn't in the data source, but requires need code logic to figure out how to render.
Upvotes: 4