开发者

ASP.NET C# GridView - variable number of columns and image thumbnail

Using GridView1.DataBind(); and AutoGenerateColumns="true" how can I find specific column and instead of URL display the thumbnail of image from that URL?

GridView is generated as result of SQL Query that might return between 2 and 10 columns (one of which might be image URL.).

For thumbnail I believe it's possible to use image.GetThumbnailImage(), but where to use it in such situation?


Generating SQL query:

if (CheckBoxUser.Checked) search_fields += "UserName";
if (CheckBoxDate.Checked) search_fields += ",EventDate";
...
if  (CheckBoxImageUrl.Checked) search_fields += ",ImageUrl";

SqlConnection conn = new SqlConnection(connectionString);
string select = "SELECT " + search_fields + " FROM TableName";
SqlDataAdapter DataCommand = new SqlDataAdapter(select, conn);
DataCommand.Fill(ds);     
GridView1.DataSource = ds.Tables[0].DefaultView;
GridView1.DataBind();

GridView1 is simply:

<asp:GridView ID="GridView1" runat="server开发者_JS百科" AutoGenerateColumns="True">
    <HeaderStyle CssClass="header_grid" />               
</asp:GridView>

There are no columns declared manually since we don't know how many columns user wants to browse. But in case he marks "ImageUrl" column then instead of network file path (\somePc\path\file.jpg) he needs to see a thumbnail of this image inside GridView.


If you know the type of your datasource and the name of the column which contains the image url, you could use the RowDataBound event like so:

Note: This would only work if you are using no other templated columns.

gridView1.RowDataBound += new GridViewRowEventHandler(gridView1_RowDataBound);

...

void gridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        DataView dataSource = (DataView)gridView1.DataSource;

        DataColumn imageUrlColumn = dataSource.Table.Columns["ImageUrl"];
        if (imageUrlColumn != null)
        {
            int index = imageUrlColumn.Ordinal;

            DataControlFieldCell cell = (DataControlFieldCell)e.Row.Controls[index];
            string imageUrl = cell.Text;

            cell.Text = GenerateThumbnailUrl(imageUrl);
        }
    }
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜