DataGridView的细胞返回NULL,而试图在数据网格细胞
我在解决方案浏览器的两个图像在该位置处显示图像 -DataGridView的细胞返回NULL,而试图在数据网格细胞
〜/图像/ Active.jpg & 〜/图像/ Inactive.jpg
我想显示这些图像在我的网格视图单元取决于单元格值,即“活动”或“无效”。
我至今尝试下面给出:
GridView的代码在页面源文件:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnDataBound="GridView1_DataBound1" DataSourceID="SqlDataSource1" BackColor="White" BorderColor="#CC9966" BorderStyle="Solid" BorderWidth="1px" CellPadding="4" >
<Columns>
<asp:BoundField DataField="ServerName" HeaderText="ServerName" SortExpression="ServerName" />
<asp:BoundField DataField="Application" HeaderText="Application" SortExpression="Application" />
<asp:BoundField DataField="Instance" HeaderText="Instance" SortExpression="Instance" />
<asp:BoundField DataField="Environment" HeaderText="Environment" SortExpression="Environment" />
<asp:TemplateField>
<ItemTemplate>
<asp:Image ID="imgID" imageurl="" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
代码隐藏文件.aspx.cs:
foreach (GridViewRow row in GridView1.Rows)
{
if (row.Cells[4].Text == "Active")
{
Image img = (Image)row.FindControl("imgID");
img.ImageUrl= "";
}
else
{
Image img = (Image)row.FindControl("imgID");
img.ImageUrl = "~/Images/Inactive.jpeg";
}
}
请注意,我不能使用rowdatabound。我已经写了上面的代码中的一个函数,我正在检查一些东西,并将单元格值更新为Active或Inactive。
出现的问题是DataGrid的Cell返回图像的空值。
请建议解决方案来解决这个问题。
尝试:
foreach (GridViewRow row in GridView1.Rows)
{
Image img = (Image)row.FindControl("imgID");
if (img!=null)
{
img.ImageUrl= (row.Cells[4].Text == "Active") ? "~/Images/Active.jpg" : "~/Images/Inactive.jpg";
}
}
我试着用你的答案,但img仍然为null。 –
您可以使用三元运算符绑定你IMAGEURL:
ImageURL='<%# Eval("Status") == "Active" ? "~/Images/Active.jpg" : "~/Images/Inactive.jpg" %>'
注:Status
是从您的数据源的值。
或者,你可以做同样的事情在你的RowDataBound事件:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Image img = (Image)e.Row.FindControl("imgID");
img.ImageURl = (e.Row.Cells[4].Text == "Active") ? "~/Images/Active.jpg" : "~/Images/Inactive.jpg";
}
}
我不会将值存储到数据库中。我正在检查服务器连接,如果它处于活动状态,则显示该服务器的gridview单元处于活动状态。 –
但这个'row.Cells [4] .Text'代码意味着你应该首先绑定单元值,否则它将为空/空。 – AsifAli72090
是row.cells [4]。文本具有“ACTIVE”或“INACTIVE”,我可以在调试时看到单元格文本是否处于活动状态。它工作正常。但在此行后,当我在调试中检查img值时,它显示为空Image img =(Image)e.Row.FindControl(“imgID”); –
感谢所有为你的答案。我通过下面的改变解决了问题。现在工作很好。 :
if (answer.Contains("INACTIVE"))
{
row.Cells[4].Text = string.Format("<img src='Images/Inactive.jpg'; height='30' width='30' />");
}
else
{
row.Cells[4].Text = string.Format("<img src='Images/Active.jpg'; height='30' width='30' />");
}
为什么你分配空 - 'img.ImageUrl =“”;'为活动?它应该是'“〜/ Images/Inactive.jpeg”;'? –
为什么不能使用行数据绑定事件? – Saurabh
@KarthickRaju,那真是空虚。但即使我把网址,它不工作。 –