0

I attach event with radiobuttonlist in code behind page, radiobuttonlist is inside a
listview .When I run program it generates an error : "object referance not set to instant of object"

.aspx code:

<asp:ListView ID="ListView1" runat="server" >
  <ItemTemplate>
       <tr><td>
  <asp:RadioButtonList ID="radiobuttonlist4" runat="server" AutoPostBack="true" 

        RepeatDirection="Horizontal"
        OnSelectedIndexChanged="selected" Width="240px">
    <asp:ListItem  Value="agree"></asp:ListItem>
       <asp:ListItem Value="disagree"></asp:ListItem>
          <asp:ListItem Value="strongagree"></asp:ListItem>
             <asp:ListItem Value="strongdisagree"></asp:ListItem>
    </asp:RadioButtonList>




</td>
       </tr>
  </ItemTemplate>
 </asp:ListView>

.aspx.cs Code

assessdal s = new assessdal();

ListView1.DataSource = s.showop1();
ListView1.DataBind();
RadioButtonList list=  ListView1.FindControl("radiobuttonlist4") as RadioButtonList;

list.SelectedIndexChanged += new EventHandler(handle);

public void handle(object sender, EventArgs e)
{
    Label2.Text = "y";      
}
user1405508
  • 35
  • 2
  • 14

2 Answers2

1

First, i fixed a ton of typos in your code.

Second, it's not finding it because FindControl is being called on ListView1, not the page (or the control hierarchy in which it exists) and FindControl only looks within that instance's child controls.

Try Page.FindControl("radiobuttonlist4") to find it in the page.

Tim Schmelter
  • 411,418
  • 61
  • 614
  • 859
Rob Rodi
  • 3,458
  • 18
  • 19
0

You should attach the event handler declaratively on the aspx, that's the easiest way.

<asp:RadioButtonList ID="radiobuttonlist4" runat="server" AutoPostBack="true" 
     RepeatDirection="Horizontal"
     OnSelectedIndexChanged="selected" 
     Width="240px">
</asp:RadioButtonList>

Since the ListView can contain multiple items, the NamingContainer of a control in it's Itemtemplate is not the ListView, but the ListViewItem. That ensures that every control gets a unique id on clientside.

So you can find your RadioButtonList in the button's click event handler in this way:

var button = (Button)sender;
var item = (ListViewItem)button.NamingContainer;
var radiobuttonlist4 = (RadioButtonList)item.FindControl("radiobuttonlist4");

If you want to "find" the RadioButtonList in it's SelectedIndexChanged event, simply cast the sender argument accordingingly (var rbl = (RadioButtonList)sender;).

Tim Schmelter
  • 411,418
  • 61
  • 614
  • 859