How can I dynamically assign the ImageUrl property of an image using data binding?

I have a SQL Server database with a table in it that lists the image file names. It is my intention to assign ImageUrl to the Image control on the page, from the data in the table. I placed the SQLDataSource control on this page, and then tried to install the FormView control and the Image control there. But I do not see how I can assign a value to the ImageUrl property through data binding.

+3
source share
3 answers

inside any type of control over your use to return data that you would do, for example ...

<asp:imagebutton id="btnId" runat="server" ImageUrl='<%# Bind("ImgUrl") %>' />

... , , datagridviews ... , .

.

  <asp:SqlDataSource
      id="SqlDataSource1"
      runat="server"
      DataSourceMode="DataReader"
      ConnectionString="<%$ ConnectionStrings:MyNorthwind%>"
      SelectCommand="SELECT LastName FROM Employees">
  </asp:SqlDataSource>

  <asp:SqlDataSource
      id="SqlDataSource2"
      runat="server"
      DataSourceMode="DataReader"
      ConnectionString="<%$ ConnectionStrings:MyNorthwind%>"
      SelectCommand="SELECT FirstName FROM Employees">
  </asp:SqlDataSource>


  <asp:ListBox
      id="ListBox1"
      runat="server"
      DataTextField="LastName"
      DataSourceID="SqlDataSource1">
  </asp:ListBox>
  <asp:ListBox
      id="ListBox2"
      runat="server"
      DataTextField="FirstName"
      DataSourceID="SqlDataSource2">
  </asp:ListBox>

,

+8

​​, , , , ItemDataBound.

, - :

Image imageToBind = e.Item.FindControl("imgTest") as Image;
image.ImageUrl = (string)DataBinder.Eval(e.Item.DataItem, "ColumnName");

, , .

+2

.aspx.cs

public string GetImage(string status)
    {
        if (status=="Active")

            return "~/images/green_acti.png";

        else

            return "~/images/red_acti.png";

    }

.aspx

 <asp:TemplateField HeaderText="|| Status ||">
          <ItemTemplate>
                <asp:Image ID="imgGreenAct" ImageUrl='<%# GetImage(Convert.ToString(DataBinder.Eval(Container.DataItem, "truck_status")))%>' AlternateText='<%# Bind("truck_status") %>' runat="server" />                            
          </ItemTemplate>
 </asp:TemplateField>
+1

Source: https://habr.com/ru/post/1774363/


All Articles