I have a peculiar case in ASP.Net Web Forms. I have a repeater in which I want to loop through a list and generate controls dynamically.
If I use <%#
,
<% for (var index = 1; index < MyNamespace.Model.Count; index++)
{ %>
<div style="font-weight: bold"><%# Eval(String.Format("v{0}_vendor_name", index.ToString())) %>: </div>
<% } %>
I can access Eval but not my loop index variable. I get below build error:
The name 'index' doesn't exist in the current context.
If I use <%=
,
<% for (var index = 1; index < MyNamespace.Model.Count; index++)
{ %>
<div style="font-weight: bold"><%= Eval(String.Format("v{0}_vendor_name", index.ToString())) %>: </div>
<% } %>
I don't get any build errors, but at run-time, I get below error:
Databinding methods such as Eval(), XPath(), and Bind() can only be used in the context of a databound control.
I have looked into a number of questions on this forum but none of them have the requirement of getting both types of variable in a single statement.
If you wonder what I'm trying to achieve, my DataTable
bound to this Repeater
has some dynamic columns. I want to add them dynamically depending on the count. So, my Eval should pick up v1_vendor_name, v2_vendor_name, if there are 2 columns.
I have v1_vendor_name
, v2_vendor_name
in the DataTable
bound to this Repeater
; Instead of using Eval("v1_vendor_name")
and Eval("v2_vendor_name")
, I'm trying to use a loop so the column in Eval
is dynamically applied. I have to do this dynamically since I have no control over the number of columns. It could go up to v10_vendor_name
.
I have tried using a property from code behind, as suggested by @tweray,
for (this.index = 1; this.index < MyNamespace.Model.Count; this.index++)
{ %>
<div style="font-weight: bold"><%# Eval(String.Format("v{0}_vendor_name", this.index.ToString())) %>: </div>
<% } %>
But, this.index
in eval always takes 0 even though I assigned 1 in the loop.