2017-07-04 82 views
0

我想要做的是:當我點擊'視圖'按鈕時,選定的行應該突出顯示。ASP.NET列表視圖改變選定的行顏色

我用Google搜索了幾個小時,但不能真正理解我錯過:

<tr height="30%"> 
    <td valign="top"> 
     <div runat="server" id="area" style="height:300px; overflow:scroll"> 
      <asp:Label ID="lbl_Result" runat="server"></asp:Label> 
      <asp:ListView ID="lv_MessageSubject" runat="server" vertical-align="top" OnSelectedIndexChanged="lv_MessageSubject_SelectedIndexChanged" OnSelectedIndexChanging="lv_MessageSubject_SelectedIndexChanging" DataKeyNames ="MessageID" OnPagePropertiesChanged="lv_MessageSubject_PagePropertiesChanged" OnPagePropertiesChanging="lv_MessageSubject_PagePropertiesChanging" OnItemDataBound="lv_MessageSubject_ItemDataBound"> 
      <LayoutTemplate> 
      <table border="1"> 
       <tr runat="server"> 
        <th runat="server"></th> 
        <th runat="server">Message</th> 
        <th runat="server">Sender</th> 
       </tr> 
       <tr runat="server" id="itemPlaceholder" /> 
      </table> 
     </LayoutTemplate> 
     <ItemTemplate> 
      <tr> 
      <td><asp:Button ID="cmd_View" runat="server" CommandName="Select" Text="View" Height="21px" /></td> 
      <td><div runat="server" id="area"><asp:Label ID="Label2" runat="server" Text='<%#Eval("Message") %>' /></div></td> 
      <td><asp:Label ID="Label3" runat="server" Text='<%#Eval("Sender") %>' /></td> 
      </tr> 
     </ItemTemplate> 
     </asp:ListView> 
     <asp:DataPager ID="DataPager" runat="server" PagedControlID="lv_MessageSubject" 
      PageSize="10"> 
      <Fields> 
       <asp:NextPreviousPagerField ShowFirstPageButton="True" ShowNextPageButton="False" /> 
       <asp:NumericPagerField /> 
       <asp:NextPreviousPagerField ShowLastPageButton="True" ShowPreviousPageButton="False" /> 
      </Fields> 
     </asp:DataPager> 
     </div> 
     </td> 
    </tr> 

我被告知使用的ItemDataBound,儘管我不知道選擇的變化如何引發的ItemDataBound。這裏是我試過的代碼:

protected void lv_MessageSubject_ItemDataBound(object sender, ListViewItemEventArgs e) 
    { 
     if (((ListView)sender).SelectedIndex == e.Item.DisplayIndex) 
     { 
      var ctrl = (HtmlContainerControl)e.Item.FindControl("area"); 
      ctrl.Attributes["style"] = "background-color:Navy; color:White; padding:0px;"; 
     } 
    } 

結果是ItemDataBound在我點擊'view'按鈕時沒有觸發。

回答

0

ItemDataBound聽起來不像是一個正確的想法。由於您的按鈕是設置防火命令,ItemCommand看起來比較合適:

<asp:ListView ... OnItemCommand="lv_MessageSubject_ItemCommand" 

... 

<asp:Button ID="cmd_View" runat="server" CommandName="Highlight" 

... 

protected void lv_MessageSubject_ItemCommand(Object sender, ListViewCommandEventArgs e) 
{ 
    if (e.CommandName == "Highlight") 
    { 
     var ctrl = (HtmlContainerControl)e.Item.FindControl("area"); 
     ctrl.Attributes["style"] = "background-color:Navy; color:White; padding:0px;"; 
    } 
} 

注意事件有不同的名稱 - 「選擇」在某種意義上special它調用了一些內置的功能,你應該不干擾這一點。

+0

它的工作原理!非常感謝你!! – ZephyrLee