2013-12-17 64 views
1

我一直试图弄清楚这一整天。我试图用3列中的SQL数据加载GridView,然后动态地将图像添加到第4列。来自SQL的数据加载正常,但无论我做什么,都无法加载图像。这里是我的代码:将图像加载到Gridview中

SqlCommand cmd1 = new SqlCommand("StoredProc", myConnection1); 
cmd1.CommandType = CommandType.StoredProcedure; 
SqlDataReader reader = cmd1.ExecuteReader(); 
while (reader.Read()) 
{ 
    if (reader["ServiceStatus"].ToString().ToLower() == "stopped") 
    { 
      ImageField status = new ImageField(); 
      status.HeaderText = "Status"; 
      status.Visible = true; 
      GridView1.Columns.Add(status); 
      status.DataAlternateTextFormatString = @"~/Images/Image.gif"; 
    } 

    GridView1.DataSource = reader; 
    GridView1.DataBind(); 
} 

我已经尝试创建一个数据表并填充它,它仍然不会工作。我知道必须有一个简单的方法来做到这一点。我错过了什么?

编辑:

我使用一个TemplateField现在,我得到一个默认的图像显示出来:

<asp:TemplateField HeaderText="Status"> 
    <ItemTemplate> 
      <asp:Image ID="Image1" runat="server" ImageUrl="~/Images/greydot.jpg"/> 
    </ItemTemplate> 
</asp:TemplateField> 

所以,我应该怎么落后,为了改变引用此IMAGEURL在我的代码图片?图像存储在解决方案中,而不是SQL。

+0

我编辑了您的标题。请参阅:“[应该在其标题中包含”标签“](http://meta.stackexchange.com/questions/19190/)”,其中的共识是“不,他们不应该”。 –

+2

您可能还需要设置[DataImageUrlField](http://msdn.microsoft.com/zh-cn/library/system.web.ui.webcontrols.imagefield.dataimageurlfield%28v=vs.110%29.aspx)为了显示任何图像,然后在** DataAlternateTextFormatString **([MSDN用法示例](http://msdn.microsoft.com/zh-cn/library/system.web.ui))中设置格式字符串。 webcontrols.imagefield.dataalternatetextformatstring%28V = vs.110%29.aspx))。 – pasty

回答

1

您可以将路径存储在数据库中,或者可以动态地给出相应图像的路径。就像这样:

ImageUrl='<%#Eval("ProductImage") 
+0

我曾考虑过这样做,但这应该是一个动态的GridView,它根据状态显示图像。我讨厌只有3张图片的整张桌子。如果我没有选择,我会沿着这条路线走下去,但必须有另一条路。 – Matt

0
protected void gvUserProfile_DataBound(object sender, EventArgs e) 
{ 
    if (e.Row.RowType == DataControlRowType.DataRow) 
    { 
     // set reference to current data record 
     // use IDataRecord if you bind to a DataReader, and DataRowView if you bind to a DataSet 
     DataRowView dataRow = (DataRowView) e.Row.DataItem; 
     string myflag = dataRow [ "yourColumnNameHere" ].ToString (); 
     if (myflag == "0") 
     { 
      // do something amusing here 
     } 
    } 
} 

2 - 如果实例上的RowDataBound任何新的控制(如您的ImageButton),你必须实例化控件添加到单元格的Controls集合。类似于

e.Row.Cells [ 0 ].Controls.Clear (); 
ImageButton img = new ImageButton (); 
img.ImageUrl = "~/images/editGray.gif"; 
e.Row.Cells [ 0 ].Controls.Add (img);