2013-12-17 62 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);