I am looking for a line of code that can show how many replies a topic has in my forum. I have a repeater(REPEATER_1) to show other info about each topic, like it's title and text. For example, to get the title, I use:
<%# DataBinder.Eval(Container, "DataItem.title")%>
This works fine, but for counting replies, I need to access another table, and count all replies for this topic. I use the following SelectCommand:
"SELECT COUNT(ID) FROM [replies] WHERE parent='" & <%# DataBinder.Eval(Container, "DataItem.ID")%> & "';"
But how do I execute this SelectCommand from within the Form (and within the repeater area) of the page using <%# XXXX.. %>
I know there are alternatives using code-behind, but I am practicing doing it this way using <%# XXXX.. %>
Also, what is it called when doing script inside a form using "<%# XXXX.. %>" ? It will make it easier for me to search on the web, as google or this website cannot search for "<%#"
I would do this in the ItemDataBound
event of the Repeater.
I'm following your current approach, but you should return the reply count with the query that gets the topics. Doing it the way you're doing it, you're calling the database too many times.
protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
// !! use a parameterized query here to avoid SQL injection
string query = String.Format("SELECT x FROM y WHERE z = {0}", DataBinder.Eval(e.Item.DataItem, "SomeColumn"));
//execute your query to get reply count
int replyCount = ExecuteQuery(query); // !! example
Label lbl = e.Item.FindControl("ReplyCountLabel") as Label;
if (lbl != null)
{
lbl.Text = replyCount.ToString()
}
}