Alvis Chen
Alvis Chen

Reputation: 47

How to retrieve a value from ListView to ASP code at the aspx page

<asp:ListView ID="ListView1" runat="server" DataKeyNames="orderID" DataSourceID="SqlDataSource1">
<ItemTemplate>
<tr>
<td>
  <asp:Label ID="statusLabel" runat="server" Text='<%# Eval("status") %>' Visible="false"  />
</td>
<% 
  Label s = (Label)ListView1.FindControl("statusLabel");
  string status = s.Text;
  if (status == "0") {  //code here }
%>
</tr>
</ItemTemplate>
</asp:ListView>

How can I get the statusLabel text at front page? not code behind. Every row of data will be different status, so I want to display buttons based on the status. Any solutions can get this done?

Upvotes: 0

Views: 773

Answers (3)

Roman
Roman

Reputation: 1665

Doing business logic inline is usually a bad idea. For your case, however, you don't need to access the statusLabel control itself. All you need is to call Eval("status") in your if statement.

So

string status = (string) Eval("status");
if (status == "0") { // etc }

Upvotes: 0

James Johnson
James Johnson

Reputation: 46077

It doesn't look like you need to get the label; you just need to get the value the label is set to, which you can do using the Eval function.

If there are a set number of buttons, you can toggle the visibility based on the status:

<ItemTemplate>
    <asp:Label ID="statusLabel" runat="server" Text='<%# Eval("status") %>' Visible="false"  />
    <asp:Button ID="Button1" runat="server" Text="Test" Visible='<%# Eval("status") == "Open" ? true : false %>' />
    <asp:Button ID="Button2" runat="server" Text="Test Again" Visible='<%# Eval("status") == "Closed" ? true : false %>' />
</ItemTemplate>

If the situation is more complex than that, you can use PlaceHolder controls to group the buttons by status:

<ItemTemplate>
    <asp:Label ID="statusLabel" runat="server" Text='<%# Eval("status") %>' Visible="false"  />
    <asp:PlaceHolder ID="plcOpenStatus" runat="server" Visible='<%# Eval("status") == "Open" ? true : false %>'>
        <!-- buttons for open status -->
    </asp:PlaceHolder>
    <asp:PlaceHolder ID="plcClosedStatus" runat="server" Visible='<%# Eval("status") == "Closed" ? true : false %>'>
        <!-- buttons for closed status -->
    </asp:PlaceHolder>
</ItemTemplate>    

Upvotes: 1

KRichardson
KRichardson

Reputation: 1010

You could attach to the ItemDataBound or ItemCreated events and then execute the code in there.

See this post for an example - http://www.toars.com/2010/11/listview-events-01/

Upvotes: 0

Related Questions