【发布时间】:2019-11-09 15:05:31
【问题描述】:
我有这些单选按钮:
<fieldset class="rating">
<input runat="server" type="radio" onclick="setRating(5);" id="star10" name="rating" value="5" /><label class = "full" for="star5" title="Excelsior! - 5 stars"></label>
<input runat="server" type="radio" onclick="setRating(4.5);" id="star9" name="rating" value="4 and a half" /><label class="half" for="star4half" title="Almost Perfect - 4.5 stars"></label>
<input runat="server" type="radio" onclick="setRating(4);" id="star8" name="rating" value="4" /><label class = "full" for="star4" title="Good - 4 stars"></label>
<input runat="server" type="radio" onclick="setRating(3.5);" id="star7" name="rating" value="3 and a half" /><label class="half" for="star3half" title="Above Average - 3.5 stars"></label>
<input runat="server" type="radio" onclick="setRating(3);" id="star6" name="rating" value="3" /><label class = "full" for="star3" title="Average - 3 stars"></label>
<input runat="server" type="radio" onclick="setRating(2.5);" id="star5" name="rating" value="2 and a half" /><label class="half" for="star2half" title="Adequate - 2.5 stars"></label>
<input runat="server" type="radio" onclick="setRating(2);" id="star4" name="rating" value="2" /><label class = "full" for="star2" title="Underwhelming - 2 stars"></label>
<input runat="server" type="radio" onclick="setRating(1.5);" id="star3" name="rating" value="1 and a half" /><label class="half" for="star1half" title="Weak - 1.5 stars"></label>
<input runat="server" type="radio" onclick="setRating(1);" id="star2" name="rating" value="1" /><label class = "full" for="star1" title="Bad - 1 star"></label>
<input runat="server" type="radio" onclick="setRating(0.5);" id="star1" name="rating" value="half" /><label class="half" title="Atrocious - 0.5 stars"></label>
</fieldset>
我想遍历它们以设置它们的状态,而不必执行switch statement 之类的操作,因此我尝试了以下操作:
for (double i = 0; i < 5; i+=0.5)
{
if(pOld.OverallRating == i)
{
//Stars are 1-10 but display as x/5 (where 5 is star10, 4.5/5 is star9 etc)
Control con = FindControl("star"+i);
((RadioButton)con).Checked = true;
}
}
我使用 FindControl 的方式似乎存在问题,但我不明白为什么 - 我得到一个空引用异常。
编辑1:
System.InvalidCastException: 'Unable to cast object of type 'System.Web.UI.HtmlControls.HtmlInputRadioButton' to type 'System.Web.UI.WebControls.RadioButton'.'
【问题讨论】:
标签: c# asp.net radio-button nullreferenceexception code-behind