我想知道当gridview中有单选按钮时我必须使用单选按钮CheckedChanged属性,并且此gridview本身位于1个用户控件内,并且用户控件位于详细视图控件内。
在我学会了如何在另一个控件中找到单选按钮控件之前。但在发现我不知道如何制作CheckedChanged属性之后呢?
protected void btnShowAddTransmittaltoCon_Click(object sender, EventArgs e)
{
Transmittallistfortest transmittalList = (Transmittallistfortest)DetailsView1.FindControl("Transmittallistfortest1");
GridView g3 = transmittalList.FindControl("GridViewTtransmittals") as GridView;
foreach (GridViewRow di in g3.Rows)
{
RadioButton rad = (RadioButton)di.FindControl("RadioButton1");
//Giving Error:Object reference not set to an instance of an object.
if (rad != null && rad.Checked)
{
var w = di.RowIndex;
Label1.Text = di.Cells[1].Text;
}
答案 0 :(得分:0)
替换此
RadioButton rad = (RadioButton)di.FindControl("RadioButton1");
用这个:
RadioButton rad = di.FindControl("RadioButton1") as RadioButton;
您不会获得异常,但可能会返回NULL
- 在这种情况下,它会被if
声明捕获:rad != null
。
使用as
关键字的重点是:
as =>不会抛出异常 - 只报告空。
顺便说一句:您应该以这种方式检索RadioButton
:
if(di.RowType == DataControlRowType.DataRow)
{
RadioButton rad = di.FindControl("RadioButton1") as RadioButton;
}
要定义CheckedChange
事件,请执行以下操作:
//rad.Checked = true;
rad.CheckedChanged += new EventHandler(MyCheckedChangeEventHandler);
然后定义处理程序:
protected void MyCheckedChangeEventHandler)(object sender, EventArgs e)
{
RadioButton rb = (RadioButton)sender;
if (rb.Checked)
{
// Your logic here...
}
}