1

我想知道当网格视图中有单选按钮并且此网格视图本身位于 1 个用户控件内且用户控件位于详细视图控件内时,我必须如何使用单选按钮 CheckedChanged 属性。

在我了解如何在另一个控件中找到单选按钮控件之前。但是在发现我不知道如何为此创建 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;
        }
4

1 回答 1

0

替换这个

RadioButton rad = (RadioButton)di.FindControl("RadioButton1");

有了这个:

RadioButton rad = di.FindControl("RadioButton1") as RadioButton;

您不会得到异常,但它可能会返回NULL- 在这种情况下,它将被捕获在if语句中:rad != null.

使用as关键字的重点是:

as => 不会抛出异常 - 它只是报告 null。


顺便说一句:你应该这样检索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...
    }
}
于 2012-10-24T15:20:04.300 回答