【问题标题】:gridview, how to build a image url in code behind?gridview,如何在后面的代码中构建图像 url?
【发布时间】:2026-02-21 01:10:01
【问题描述】:

我有一个包含图像字段的 gridview 控件。但是,图像 url 是由我返回的数据集中的几个字段构建的。你如何将这些字段连接在一起,在什么时候我应该这样做,以便我可以在我的 gridview 中传递该图像 url 做我的图像字段?我猜它在 RowDataBound 上,但我不知道如何访问数据集中的每一行?

谢谢。

【问题讨论】:

    标签: c# visual-studio-2008 .net-3.5 gridview


    【解决方案1】:

    如果没有代码示例,我不确定您要连接什么,但是我会在绑定 gridview 之前执行连接并将其存储在类的私有成员中,以便您稍后可以在 RowDataBound 事件。

    您可以使用行数据绑定事件在该行中查找控件并设置其ImageUrl 属性。

    private string m_ConcatUrl;
    
    protected void gridView_RowDataBound(Object sender, GridViewRowEventArgs args)
    {
        if(args.Row.RowType == DataControlRowType.DataRow)
        {
            Image imgCtrl = (Image) args.Row.FindControl("imgCtrl");
            imgCtrl.ImageUrl = m_ConcatUrl;
        }
    }
    

    【讨论】:

      【解决方案2】:

      您可以使用 RowDataBound 事件来设置单元格值。

      void YourGridView_RowDataBound(Object sender, GridViewRowEventArgs e)
        {
      
          if(e.Row.RowType == DataControlRowType.DataRow)
          {
            // You can set your cell value in this
            e.Row.Cells[index] // use this to set the value in the cell 
          }
      
        }
      

      【讨论】:

        【解决方案3】:

        在 .NET 4 中,它会是这样的:

        if (e.Row.RowType == DataControlRowType.DataRow)  
        {  
            string1 = e.Row.Cells[i].Text;
        }
        

        i 是您要引用的特定列的索引(例如,Cells[0] 是列 1)。

        我不确定它在 3.5 中是否有所不同,但请尝试一下。

        【讨论】: