Gridview rowdatabound access data items vb

六月ゝ 毕业季﹏ 提交于 2019-12-02 14:39:41

问题


I am trying to an ImageUrl to an image in a Template Field in GridView but keep getting the error:

Object reference not set to an instance of an object. on this line:

Dim imagePath As String = rowView("image_path")

I've never done this before on a GridView but had it working on a ListView.

Thanks for any help heres my code:

.APSX

        <asp:GridView ID="gvImages" DataKeyNames="id" runat="server" AutoGenerateColumns="False" BorderWidth="0px" GridLines="None">
        <Columns>
            <asp:TemplateField>
                <ItemTemplate>
                    <asp:CheckBox ID="imageId" runat="server" />
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField>
                <ItemTemplate>
                    <asp:Image ID="imageFile" runat="server"></asp:Image>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:BoundField DataField="id" />
        </Columns>
    </asp:GridView>

CODE BEHIND

Protected Sub gvImages_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gvImages.RowDataBound

    Dim rowView As DataRowView = CType(e.Row.DataItem, DataRowView)

    Dim imagePath As String = rowView("image_path")

    Dim strImageUrl As String = "~/admin/images/cases/" & Request.QueryString("uid") & "/" & imagePath

    Dim imageFile As System.Web.UI.WebControls.Image = CType(e.Row.FindControl("imageFile"), System.Web.UI.WebControls.Image)
    imageFile.ImageUrl = strImageUrl

End Sub

回答1:


I think you need to check that its a data row and not the header row

Try this

Protected Sub gvImages_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gvImages.RowDataBound

    If e.Row.RowType = DataControlRowType.DataRow Then

        Dim rowView As DataRowView = CType(e.Row.DataItem, DataRowView)

        Dim imagePath As String = rowView("image_path")

        Dim strImageUrl As String = "~/admin/images/cases/" & Request.QueryString("uid") & "/" & imagePath

        Dim imageFile As System.Web.UI.WebControls.Image = CType(e.Row.FindControl("imageFile"), System.Web.UI.WebControls.Image)
        imageFile.ImageUrl = strImageUrl

    End If
End Sub



回答2:


try

Dim imagePath As String = e.rowView("image_path").ToString()

If the table binded with the grid has column "image_path", then instead use an easier way....

<asp:Image id="img1" runat="server" imageUrl = '<%#Eval("image_path")%>' />

If you want to build some custome string

imageurl = '<%# String.Format("{0} - {1} - {2} - {3}", Eval("Name1"), Eval("Name2"), Session["abc"],Request["abc"]) %>'


来源:https://stackoverflow.com/questions/5232214/gridview-rowdatabound-access-data-items-vb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!