在 ItemDatabound 的数据列表中更改 link 按钮前景色

Change link button fore color inside datalist on ItemDatabound

您好,我正在尝试根据网络、copychimp、复制器和驱动器的情况更改 link 按钮的颜色 space 我试过这个:

protected void dgrMachines_ItemDataBound(object sender, DataListItemEventArgs e)
{
    string copychimp = Convert.ToString(DataBinder.Eval(e.Item.DataItem, "copychimp"));
    string network = Convert.ToString(DataBinder.Eval(e.Item.DataItem, "network_isconnected"));
    string drive = Convert.ToString(DataBinder.Eval(e.Item.DataItem, "drive_alert"));
    string replicator = Convert.ToString(DataBinder.Eval(e.Item.DataItem, "replicator_isactive"));

    if (network == "0" || copychimp == "Disconnected" || drive == "1" || replicator == "0")
    {
        e.Item.ForeColor = System.Drawing.Color.Red;  
    }
    else
    {
        e.Item.ForeColor = System.Drawing.Color.Green;  
    }
}

运气不好

但是当我尝试用户将 e.Item.ForeColor = System.Drawing.Color.Green; 更改为 e.Item. e.Item.BackColor = System.Drawing.Color.Green;
这行得通。 这是我的 html:

<asp:DataList ID="dgrMachines" runat="server" RepeatColumns="5" OnSelectedIndexChanged="dgrMachines_SelectedIndexChanged" OnItemCommand="dgrMachines_ItemCommand" CellPadding="3" CssClass="col-12" OnItemDataBound="dgrMachines_ItemDataBound">
    <HeaderTemplate>
        <div class="container col-12" style="background-color: #333333">
            <b>
                <h2 class="text-center" style="color: white">Machines List</h2>
            </b>

        </div>

    </HeaderTemplate>
    <ItemTemplate>
        <asp:LinkButton ID="lblMachine" Text='<%# Eval("machine") %>' runat="server" Font-Size="Medium" ForeColor="Black"></asp:LinkButton>
       <%-- <asp:label ID="lblcopychimp" runat="server" Text='<%# Eval("copychimp") %>' />
        <asp:label ID="lblNetwork" runat="server" Text='<%# Eval("network_isconnected") %>' />
        <asp:label ID="lblreplicator" runat="server" Text='<%# Eval("replicator_isactive") %>' />
         <asp:label ID="lbldrive" runat="server"  Text='<%# Eval("drive_alert") %>' />--%>

        <%--   <%#Eval("machine")%> --%>
    </ItemTemplate>
</asp:DataList>

有人能帮我解决这个问题吗?

您需要使用FindControl:

Use FindControl to access a control from a function in a code-behind page, to access a control that is inside another container, or in other circumstances where the target control is not directly accessible to the caller. This method will find a control only if the control is directly contained by the specified container; that is, the method does not search throughout a hierarchy of controls within controls.

所以应该是这样的:

LinkButton machineButton = (e.Item.FindControl("lblMachine") as LinkButton);
if (machineButton != null)
{
    machineButton.ForeColor = System.Drawing.Color.Red;
}

而不是:

e.Item.ForeColor = System.Drawing.Color.Red;