Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
743 views
in Technique[技术] by (71.8m points)

asp.net - how to have one of the column in gridview to be an image?

I have a gridview that gets created in codebehind.

In the below code, I would like to have 3rd column to be some image (Example: PDF icon or similar).

I am thinking Type.GetType needs to be changed for column named "Image"??

DataTable dt = new DataTable();
GridView gview = new GridView();
DataRow dr;
DataColumn dc = new DataColumn("Description", Type.GetType("System.String"));
dt.Columns.Add(dc);
dc = new DataColumn("Image", Type.GetType("System.String"));
dt.Columns.Add(dc);
dc = new DataColumn("Size (MB)", Type.GetType("System.String"));
dt.Columns.Add(dc);
{
    dr = dt.NewRow();
    dr["Description"] = item["Name"];
    dr["Size (MB)"] = item["Size"];
    dr["Image"] = "pdf.gif"; // put complete reference here,
    dt.Rows.Add(dr);
}
gview.DataSource = dt;
gview.DataBind();
Controls.Add(gview);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Just store the image URL in the DataTable rather than the actual image. Then, use a TemplateField in your GridView and put an Image in the ItemTemplate:

<asp:TemplateField>
    <ItemTemplate>
        <asp:Image ID="Image1" runat="server" ImageUrl='<%# Eval("ImageUrlColumn") %>' ... />
    </ItemTemplate>
</asp:TemplateField>

You can also use an ImageField:

<asp:ImageField DataImageUrlField="ImageNameColumn" DataImageUrlFormatString="/images/{0}"></asp:ImageField>

EDIT

When declaring columns, try this instead:

dt.Columns.Add("Image", typeof(string));

And to set the value of the image column, try this:

dr.SetField<string>("Image", "img.png");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...