开发者

Display image in Gridview column, column needs to be created dynamically

I need to display an image within a GridView control. The column creation needs to be dynamic. In other words th开发者_C百科e entire column creation needs to be done within the code.

Lots of postings refer to http://msdn.microsoft.com/en-us/library/aa479350.aspx. The problem is that I need the columns to be created dynamically, since I don't know in advance if the image column would display. Also, that article may be old since its still referencing asp.net version 2.0. I'm developing it in vs2010 which I believe uses asp.net version 3.5 (or greater)


If you want a truly dynamic grid, then you can build your grid in code. It's a little tricky but not impossible. Here is a self contained example which you can take a look at.

<%@ Page Language="C#" AutoEventWireup="true"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">

    class MyItemTemplate : System.Web.UI.ITemplate
    {

        public void InstantiateIn(System.Web.UI.Control container)
        {
            Label label = new Label();
            label.ID = "MyLabel";
            container.Controls.Add(label);
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        GridView gv;
        if (!this.IsPostBack)
        {
            gv = new GridView();
            gv.AutoGenerateColumns = false;
            gv.ID = "MyGrid";
            var column = new TemplateField();
            column.HeaderText = "My Item";
            column.ItemTemplate = new MyItemTemplate();
            gv.Columns.Add(column);
            MyDiv.Controls.Add(gv);
            gv.RowDataBound += new GridViewRowEventHandler(gv_RowDataBound);
        }

        var dataSource = new string[] { "a", "b", "c" };
        gv = this.Page.FindControl("MyGrid") as GridView;

        gv.DataSource = dataSource;
        gv.DataBind();
    }

    void gv_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        var label = e.Row.FindControl("MyLabel") as Label;
        if (label != null)
            label.Text = ((string)e.Row.DataItem).ToUpper();
    }
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div id="MyDiv" runat="server">

    </div>
    </form>
</body>
</html>
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜