开发者

Showing icon conditionally in C#/ASP.NET

I am having trouble with my GridView in ASP.NET, which is listing a few rows of documents. Some of the rows (i.e. documents) are unpaid and need a shopping icon, which takes the clicker to another page completely.开发者_StackOverflow Other rows need no icon since they are paid.

This is what I have so far, although HyperLink is throwing an error saying that it cannot cast a HyperLinkField to a HyperLink. Any ideas? Is it better to create an object of the HyperLinkField through C# instead of ASP for example?

All help is much, much, much appreciated!

//Jenny

protected void getImages(Object src, GridViewRowEventArgs e)
{
     if (e.Row.RowType == DataControlRowType.DataRow)
            {
                BusinessClasses.BusinessEntities.DocumentEntity dataRow = (BusinessClasses.BusinessEntities.DocumentEntity)e.Row.DataItem;
                string status = dataRow.Status.ToString();

                TableCellCollection myCells = e.Row.Cells;
                if (status == "UnPaid")
                {
                    HyperLink planLink = (HyperLink)myCells[myCells.Count - 1].Controls[0];
                    planLink.ImageUrl = string.Format("~/Images/Icons/icon_buy.png/");
                    planLink.ToolTip = "Köp";
                }
            }
        }


I'd convert your hyperlink field to a Template Field with a hyperlink inside of it. Then, the code that you are using, should work.

A hyperlinkfield is not a hyperlink.

Here is an example:

<asp:TemplateField>
   <ItemTemplate>
      <asp:HyperLink ID="link" runat="server"/>
   </ItemTemplate>
</asp:TemplateField>


In this kind of case I usually just use a TemplateColumn with a conditional expression based on the data, and not bother with coding the condition in code-behind.

<asp:TemplateColumn HeaderText="Status">
  <%#
       (Container.DataItem("Status")=="Unpaid" ?
       "<a href='something'><img src='icon1' /></a>" : 
        string.Empty)  
   %>
</asp:TemplateColumn>


I think you should use a simpler solution. All data you need are accessible through Eval so no need to write event handlers, and your cast will not work because HyperLinkField is not an HyperLink.

So all you need is to create an template field with an hyperlink and use Eval to show/hide the icon like the example bellow:

<asp:TemplateField HeaderText="Status">
  <ItemTemplate>
    <asp:HyperLink ID="HyperLink1" runat="server" ImageUrl="~/Images/Icons/icon_buy.png/" 
      ToolTip="Köp" NavigateUrl="Your nav path here" 
      Visible='<%# Eval("Status").ToString()=="UnPaid" %>' ></asp:HyperLink>
  </ItemTemplate>
</asp:TemplateField>

Don't forget to remove the event handler ;)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜