【问题标题】:How to access a control in an .aspx page [duplicate]如何访问.aspx页面中的控件[重复]
【发布时间】:2012-06-04 22:35:00
【问题描述】:

我在页面后面的代码中使用radiobuttonlist 附加事件,单选按钮列表位于a
listview 内。当我运行程序时,它会生成一个错误: “对象引用未设置为对象的瞬间”

.aspx 代码:

<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 代码

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";      
}

【问题讨论】:

  • 请格式化您的代码,Listview的哪个模板是RadioButtonList?
  • soory,.aspx 代码中有单选按钮列表控件,在复制代码时,它被遗漏了..
  • @user1405508:你为什么不正确地编辑你的问题?所以其他人可以提供帮助!
  • @user1405508:你想在哪里找到你的 RadioButtonList?你已经展示了你的代码隐藏在哪里?

标签: c# asp.net .net radiobuttonlist


【解决方案1】:

首先,我修正了您代码中的大量拼写错误。

其次,它没有找到它,因为FindControl 是在ListView1 上调用的,而不是页面(或它所在的控件层次结构),FindControl 只在该实例的子控件中查找。

尝试Page.FindControl("radiobuttonlist4")在页面中找到它。

【讨论】:

  • 但是 radiobuttonlist 在 listview 中。所以我们在 listview 中找到它
  • 但是 radiobuttonlist 在 listview 中。所以我们在 listview 中找到它
【解决方案2】:

您应该在 aspx 上以声明方式附加事件处理程序,这是最简单的方法。

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

由于ListView 可以包含多个项目,因此Itemtemplate 中的控件的NamingContainer 不是ListView,而是ListViewItem。这样可以确保每个控件在客户端都获得一个唯一的 ID。

所以你可以通过这种方式在按钮的点击事件处理程序中找到你的RadioButtonList

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

如果您想在其 SelectedIndexChanged 事件中“找到” RadioButtonList,只需相应地转换 sender 参数 (var rbl = (RadioButtonList)sender;)。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多