开发者

Conditional image in datagrid

开发者 https://www.devze.com 2022-12-16 18:44 出处:网络
I have a datagrid in asp.net and vb.net, and i\'d like to show the status of the item of a certain row with two possible icons.

I have a datagrid in asp.net and vb.net, and i'd like to show the status of the item of a certain row with two possible icons.

开发者_开发问答What would be the easiest way of doing so?

I have a function that checks validation and returns a boolean value that uses some fields of the datagrid.

(you can answer in c#)


You'll want to decide which image to load in your page code-behind.

protected void Page_Init(object sender, EventArgs e)
{
  // first you have to hook up the event
  datagrid.ItemDataBound += datagrid_ItemDataBound;
}

// once the grid is being bound, you have to set the status image you want to use
private void datagrid_ItemDataBound(object sender, DataGridItemEventArgs e)
{
  if(e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item) {
    Image img = (Image)e.Item.FindControl("ImageControlName");
    if( ValidationFunction() ) {
      img.ImageUrl = "first_status_image.jpg";
    } 
    else 
    {
      img.ImageUrl = "second_status_image.jpg";
    }
  }
}


I should say your best bet is to do it with a TemplateColumn and some code:

<asp:DataGrid runat="server" ID="DataGrid1" AutoGenerateColumns="false">
    <Columns>
        <asp:TemplateColumn>
            <ItemTemplate>
                <asp:Image runat="server" ID="RowImage" />
            </ItemTemplate>
        </asp:TemplateColumn>
    </Columns>
</asp:DataGrid>

Private Sub DataGrid1_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs) Handles DataGrid1.ItemDataBound

    Dim imageControl As Image

    If e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem Then
        imageControl = DirectCast(e.Item.FindControl("RowImage"), Image)

        If MyValidationFunction() Then
            imageControl.ImageUrl = "icon1.gif"
        Else
            imageControl.ImageUrl = "icon2.gif"

        End If
    End If

End Sub
0

精彩评论

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