Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/34.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 更改itemdatabound上asp中继器内div的颜色_C#_Asp.net_Repeater - Fatal编程技术网

C# 更改itemdatabound上asp中继器内div的颜色

C# 更改itemdatabound上asp中继器内div的颜色,c#,asp.net,repeater,C#,Asp.net,Repeater,我正在尝试更改itemdatabound事件中继器中div的颜色。 我试过在itemdatabound中使用一个面板,就像这样 protected void rptLocations_ItemDataBound(object sender, RepeaterItemEventArgs e) 然后在里面 Panel cblock = e.Item.FindControl("pnlColour") as Panel; cblock.Style.Add("background", rndColour

我正在尝试更改itemdatabound事件中继器中div的颜色。 我试过在itemdatabound中使用一个面板,就像这样

protected void rptLocations_ItemDataBound(object sender, RepeaterItemEventArgs e)
然后在里面

Panel cblock = e.Item.FindControl("pnlColour") as Panel;
cblock.Style.Add("background", rndColour);
但这带来了一个错误:

Object reference not set to an instance of an object. 
  Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

 Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
无论如何,我宁愿使用一个面板上的div

是否有任何方法可以从itemdatabound事件更改div的颜色


提前谢谢

您有两个问题。第一,有两种方法可以为div或Panel添加背景色

第二,cblock变量很可能为null。通过检查RepeaterItem的类型,确保在ItemDataBound中仅在需要时搜索cblock。此示例检查RepeaterItem是否不在HeaderTemplate或FooterTemplate中,而是在ItemTemplate或AlternatingItemTemplate中


我用HTMLControl解决了这个问题

我使用HtmlGenericControl设置样式属性

((HtmlGenericControl)(e.Item.FindControl("divColour"))).Attributes["style"] += ("background:" + rndColour + ";)");

简单有效

是否在ItemDataBound事件中检查项和RepeatingItem?此外,在向cblock添加类之前,可能需要检查cblock是否为null,以便应用程序不会崩溃!对不起,我应该澄清一下,我会解决这个问题。您可能还想将标记从asp classic更改为asp.net,以获得更好的响应。
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
    Panel cblock = e.Item.FindControl("pnlColour") as Panel;
}
((HtmlGenericControl)(e.Item.FindControl("divColour"))).Attributes["style"] += ("background:" + rndColour + ";)");