如何根据数据库的某些属性值在gridview内设置图像的图像URL?

时间:2013-12-31 08:13:32

标签: c# asp.net gridview

我在gridview中有一个图像控件以及其他属性。我想知道如何设置图像网址属性或如何根据属性值指定客户名称来指定某些静态图像?我想这样做,因为我没有在我的数据库中存储图像。请指导我如何做到这一点?我是否需要使用gridview的RowDataBound属性?

我想尝试这样的事情 -

dt = g1.return_dt("select cust_name from tbl_details");
if(dt.Rows.Equals("XYZ"))
{
Set Image Url
}
else if(dt.Rows.Equals("XXX"))
{
Set Image Url
}

2 个答案:

答案 0 :(得分:2)

表:“tblA”

id     int    identity
name   nvarcher(50)  

ASPX:

<asp:GridView ID="GridView1" runat="server" OnRowDataBound="GridView1_RowDataBound">
        <Columns>
            <asp:TemplateField>
                <ItemTemplate>
                    <asp:Image ID="Image1" runat="server" />
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
</asp:GridView><br />
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
         ConnectionString="<%$ ConnectionStrings:ConnectionString %>" 
        SelectCommand="SELECT * FROM [tblA]">
</asp:SqlDataSource>

代码背后:

protected void Page_Load(object sender, EventArgs e)
{
        //fill gridview
        if( ! IsPostBack )
        {
            GridView1.DataSource = SqlDataSource1;
            GridView1.DataBind();
        }
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
        string name = e.Row.Cells[2].Text;            
        Image img = (Image)e.Row.FindControl("Image1");
        if (img==null)
        {
            return;
        }
        if(name == "XYZ")
        {
            img.ImageUrl = "~/Images/a.jpg";
        }
        else if(name == "XPS")
        {
              img.ImageUrl = "~/Images/b.jpg";
        }
        else
        {
            //default static image
            img.ImageUrl = "~/Images/c.jpg";
        }
}

答案 1 :(得分:0)

试试这个

<强> ASPX

<asp:GridView ID="GridView3" runat="server"   
              AllowPaging="True" DataKeyNames="DangerDownstream"
              onpageindexchanging="GridView3_PageIndexChanging" 
              backcolor="White" onrowdatabound="GridView3_RowDataBound"
              PageSize="5" Width="100%" AutoGenerateColumns="False"
              EnableModelValidation="True">
        <RowStyle CssClass="station_grid" />              
        <Columns>
          <asp:BoundField DataField="DangerDownstream" />
             <asp:TemplateField HeaderText="Notification">
                <ItemTemplate>
                  <asp:Image ID="Img" runat="server" Height="25px" Width="25px"/>
                  <asp:Label ID="Ln" runat="server" Text="Label"></asp:Label>
                 </ItemTemplate>
               </asp:TemplateField>
         </Columns>
</asp:GridView>

<强> CS

System.Web.UI.WebControls.Image img = (System.Web.UI.WebControls.Image)e.Row.Cells[2].FindControl("Img"); 
img.ImageUrl = "~/Images/warning2.png";