In Gridview Set Image Column programatically

In Gridview I have column representing Thumbnail image which works fine.:
            <asp:ImageField DataImageUrlField="PicFile1"
DataImageUrlFormatString="Images/A009/Thumbs/{0}">
            </asp:ImageField>

I want the fixed 'A009' to be replaced by Session variable - "ClCode"

VB in code-behind I have:
iPicFile = ImageString & Session("ClCode") & "/Thumbs/{0}"
How can "iPicFile" variable be used in DataImageUrlFormatString?
With thanks
eharfordAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

TechTiger007Commented:
Inside RowDataBound event handler for the grid view say
dim img as ImageButton  = e.Row.FindControl(imagebuttonid) as ImageButton
img.ImageURL = ImageString & Session("ClCode") & "/Thumbs...."
0
prairiedogCommented:
A little modification of TechTiger007's solution:
dim img as ImageButton  = e.Row.Cells(i).Controls(0) as ImageButton 'Change "i" to the actual index of the ImageField in GridView.

0
eharfordAuthor Commented:
Thanks for your suggestion. I am getting "End of Statement expected" on "ImageButton":
Code:
Protected Sub dgPInv_RowDatabound(ByVal sender As Object, ByVal e as System.Web.UI.WebControls.GridViewRowEventArgs) Handles dgPInv.RowDataBound
Dim img As ImageButton = e.Row.Cells(12).Controls(0) as ImageButton
img.ImageURL = ImageString & Session("ClCode") & "/Thumbs/{0}"
End Sub
0
Cloud Class® Course: Microsoft Azure 2017

Azure has a changed a lot since it was originally introduce by adding new services and features. Do you know everything you need to about Azure? This course will teach you about the Azure App Service, monitoring and application insights, DevOps, and Team Services.

prairiedogCommented:
Try this:

Dim img As ImageButton = CType(e.Row.Cells(12).Controls(0), ImageButton)

Open in new window

0
eharfordAuthor Commented:
Your suggestion sorted the End of statement problem. I am now getting an ArgumentOutOfRangeException.
I understand that "e.Row.Cells(12)" represents the Column in the Gridview. What does ".Controls(0)" represent?
With thanks.
0
prairiedogCommented:
Wait a second. This is an ImageField, not ImageButton. My apology. Use this line:

Dim img As Image = CType(e.Row.Cells(12).Controls(0), Image)

Controls(0) represents the first control in Cell(12).

Make sure the ImageField is the 13th column of your GridView.


0
eharfordAuthor Commented:
Apologies for labouring this problem. I have created the gridview using the SQLDatabase wizard and bound grid to it. I have ImageField as 13th column in grid as follows:
<asp:ImageField DataImageUrlField="PicFile1"></asp:ImageField>
PicFile1 holds the image file name.
I also have following code in code-behind:
Protected Sub dgPInv_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles dgPInv.RowDataBound
Dim img As Image = CType(e.Row.Cells(12).Controls(0), Image)
img.ImageUrl = ImageString & Session("ClCode") & "/Thumbs/"
End Sub
I am still getting System.ArgumentOutOfRangeException was unhandled by user code
  Message="Specified argument was out of the range of valid values.
Parameter name: index"
  ParamName="index"
  Source="System.Web"

How do I refer to the variable file name in the ImageUrl line? I was using {0}.
With thanks
 
0
prairiedogCommented:
Can you post your GridView code (ASPX file)?
0
eharfordAuthor Commented:
Dont seem to be able to send aspx files  within or without zip file.
ASPX file:
<%@ Page Language="VB" MasterPageFile="~/MasterPage.master" AutoEventWireup="false" CodeFile="Invent2.aspx.vb" Inherits="Invent2" title="Constantine Ltd - Inventory Paged" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
    <asp:Button ID="cmdAll" runat="server" Text="Invent - All" Width="85px" />
    <asp:Button ID="cmdBack" runat="server" Text="Back" Width="85px" />
    <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:Connectstring %>"
        SelectCommand="cClInv" SelectCommandType="StoredProcedure">
        <SelectParameters>
            <asp:SessionParameter Name="clCode" SessionField="ClCode" Type="String" />
        </SelectParameters>
    </asp:SqlDataSource>
    <asp:GridView ID="dgPInv" runat="server" AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False"
        DataKeyNames="InventNo" DataSourceID="SqlDataSource1" Width="967px">
        <Columns>
            <asp:CommandField ButtonType="Button" ShowSelectButton="True" />
            <asp:BoundField DataField="Location" HeaderText="Location" SortExpression="Location" />
            <asp:BoundField DataField="clInventNo" HeaderText="Client InvNo" SortExpression="clInventNo" />
            <asp:BoundField DataField="clInventNo2" HeaderText="Cat No" SortExpression="clInventNo2" />
            <asp:BoundField DataField="ArtistMaker" HeaderText="Artist" SortExpression="ArtistMaker" />
            <asp:BoundField DataField="ShortDesc" HeaderText="Title" SortExpression="ShortDesc" />
            <asp:BoundField DataField="iDate" HeaderText="Date" SortExpression="iDate" />
            <asp:BoundField DataField="Medium" HeaderText="Medium" SortExpression="Medium" />
            <asp:BoundField DataField="Height" HeaderText="Length" SortExpression="Height" />
            <asp:BoundField DataField="Width" HeaderText="Width" SortExpression="Width" />
            <asp:BoundField DataField="Depth" HeaderText="Height" SortExpression="Depth" />
            <asp:BoundField DataField="AcquPriceEquiv" DataFormatString="{0:C}" HeaderText="Value"
                HtmlEncode="False" SortExpression="AcquPriceEquiv" />
            <asp:ImageField DataImageUrlField="PicFile1"></asp:ImageField>
        </Columns>
        <HeaderStyle BackColor="Navy" Font-Size="Small" ForeColor="White" />
        <PagerSettings Position="TopAndBottom" Mode="NumericFirstLast" FirstPageText="First &amp;lt;&amp;lt;" LastPageText="Last &amp;gt;&amp;gt;" />
        <PagerStyle Font-Size="Small" />
    </asp:GridView>
  </asp:Content>
 
Vb file:
Partial Class Invent2
    Inherits System.Web.UI.Page
    Private ImageString As String = ConfigurationSettings.AppSettings("ImagePath")
 
    Protected Sub dgPInv_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles dgPInv.RowDataBound
        Dim img As Image = CType(e.Row.Cells(12).Controls(0), Image)
        img.ImageUrl = ImageString & Session("ClCode") & "/Thumbs/"
    End Sub
    Protected Sub dgPInv_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles dgPInv.SelectedIndexChanged
        Dim index As Integer = dgPInv.SelectedIndex
        Response.Redirect("InvPart.aspx?txtInvNo=" + Me.dgPInv.DataKeys(index).Value.ToString)
    End Sub
 
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Session("Private") = False Then Response.Redirect("Default.aspx")
    End Sub
 
    Protected Sub cmdAll_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdAll.Click
        Response.Redirect("Invent.aspx?txtClCode=" + Session("ClCode"))
    End Sub
 
    Protected Sub cmdBack_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdBack.Click
        Response.Redirect("Account.aspx?txtClCode=" + Session("ClCode"))
    End Sub
End Class

Open in new window

0
prairiedogCommented:
OK, you will need to check if the row is a DataRow before you can use FindControl
Protected Sub dgPInv_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles dgPInv.RowDataBound 
If (e.Row.RowType = DataControlRowType.DataRow) Then
  Dim img As Image = CType(e.Row.Cells(12).Controls(0), Image) 
  img.ImageUrl = ImageString & Session("ClCode") & "/Thumbs/" 
End If
End Sub 

Open in new window

0
prairiedogCommented:
Sorry, I should have caught the fact earlier that you are missing "If (e.Row.RowType.." in your RowDataBound event handler.
0
eharfordAuthor Commented:
I am still not getting the image file name into img.imageurl. The properties of the image in the grid is coming through as the path only. How do I get the file name from the data source?
I am nearly there - I am very grateful to you.
0
prairiedogCommented:
In your original post, you have this:
iPicFile = ImageString & Session("ClCode") & "/Thumbs/{0}"

Where do you do this?
0
eharfordAuthor Commented:
I was using:
DataImageUrlFormatString="Images/A009/Thumbs/{0}">
in the properties of the image column in the grid
and
iPicFile = ImageString & Session("ClCode") & "/Thumbs/{0}"
in the code-behind
I have set in the properties of the ImageField in the grid:
<asp:ImageField DataImageUrlField="PicFile1"></asp:ImageField> and am trying to add the value of PicFile1 to the iPicFile string.
0
prairiedogCommented:
If you define your ImageField as described in your original post:
<asp:ImageField DataImageUrlField="PicFile1"
DataImageUrlFormatString="Images/A009/Thumbs/{0}">
            </asp:ImageField>

then when the GirdView is bound, {0} will be replaced with the value of "PicFile1" automatically. So what you want is to replace "A009" with a Session variable Session("CICode"), is it right? If yes, then you can do this as attached code snippet. If not, please let me know.
Also, you mentioned a couple of times that in code-behind, you have iPicFile = ImageString & Session("ClCode") & "/Thumbs/{0}", but it does not make sense to me because you can't have "{0}" in your string concatenation. Moreover, "in code-behind" does not help me understand: where exactly (in what event handler ) do you have that line of code? What is ImageString?

Protected Sub dgPInv_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles dgPInv.RowDataBound 
If (e.Row.RowType = DataControlRowType.DataRow) Then
  Dim img As Image = CType(e.Row.Cells(12).Controls(0), Image) 
  img.ImageUrl = img.ImageUrl.Replace("A009", Session("CICode")) 
End If
End Sub 

Open in new window

0
eharfordAuthor Commented:
Many, many thanks - that works perfectly. In summary I have been struggling between the aspx and the code behind file
ImageString is the variable I was using to bring the path in from the web.config.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
eharfordAuthor Commented:
Done
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
ASP.NET

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.