0

Is it possible to perform a SQL SELECT Statement that will select all rows, then output the rows to a label, which is created dynamically?

In the system I'm writing (pretty new to c#) I am performing a SQL SELECT from a view where a records ID can appear multiple times, but with different associated values, i.e.

ID - VALUE    
1 - A    
1 - B    
1 - C    
2 - A    
2 - B    
3 - A

What I want to do then is output each result to a its own label, but i would have no idea until the SELECT is ran how many labels I would need so I'd need code to draw them dynamically? Using the above examples A would return 3 labels, but B would only return 2.

If that makes any sense? E.G

foreach (result in sql)
{
 label.Text = result
}

Thanks

2
  • 1
    You should use a Repeater control to handle this. Commented May 11, 2015 at 17:34
  • What you want to do is certainly possible. You need to research "dynamically create controls in asp.net". However, if at all possible I would encourage you to find a way to display the data without creating controls. Gridview and even repeaters are a better solution. Commented May 11, 2015 at 17:34

1 Answer 1

1

You can use a repeater to do this.

https://msdn.microsoft.com/en-us/library/zzx23804(v=vs.85).aspx

  <asp:Repeater ID="labelRepeater" runat="server" 
      DataSourceID="labelDataSource">
      <ItemTemplate>
            <asp:Label runat="server" ID="Label1" 
                text='<%# Eval("Value") %>' />
      </ItemTemplate>
  </asp:Repeater>

  <asp:SqlDataSource 
      ConnectionString=
          "<%$ _fill_in_your_string %>"
      ID="labelDataSource" runat="server" 
      SelectCommand="SELECT ID, Value from myTable">
  </asp:SqlDataSource>

Look here also: possible duplicate? How to add Repeater control dynamically from code behind?

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.