好吧...在网上搜索了大约 100 个答案,没有任何效果,所以我显然不明白。
我有一组动态创建的选项卡。当用户单击其中一个选项卡时,它应该更改为该选项卡及其内容。但是,每次我尝试这样做时,都会收到以下错误消息:
ActiveViewIndex 被设置为“0”。它必须小于当前视图控件的数量“0”。对于动态添加的视图,请确保在 Page_PreInit 事件之前或中添加它们。
这是 ASP.NET 代码:
<table width="90%" align="center">
<tr>
<td>
<asp:Panel ID="buttonPanel" runat="server" />
<asp:MultiView ID="ProfileView" runat="server">
</asp:MultiView>
</td>
</tr>
</table>
这是 C# 代码:
Button[] _tabs; //tabs for the profile
View[] _views; //views inside of the MainView
string[] _tabTitles = { "Main", "Website Stats", "About", "Other",
"Wall", "Posts", "Topics", "Pictures" };
protected void Page_PreInit(object sender, EventArgs e)
{
CreateTabs();
}
protected void Page_Load(object sender, EventArgs e)
{
for (int i = 0; i < _tabs.Length; i++)
{
buttonPanel.Controls.Add(_tabs[i]);
ProfileView.Controls.Add(_views[i]);
}
_tabs[0].CssClass = "Clicked";
ProfileView.ActiveViewIndex = 0;
}
protected void CreateTabs()
{
_tabs = new Button[_tabTitles.Length];
_views = new View[_tabTitles.Length];
for (int i = 0; i < _tabs.Length; i++)
{
_views[i] = new View();
_views[i].ID = _tabTitles[i] + "View";
_tabs[i] = new Button();
_tabs[i].CssClass = "Initial";
_tabs[i].BorderStyle = BorderStyle.None;
_tabs[i].Text = _tabTitles[i];
_tabs[i].Click += TabClick;
}
}
protected void TabClick(object sender, EventArgs e)
{
for (int i = 0; i < _tabs.Length; i++)
{
if ((sender as Button) == _tabs[i])
{
_tabs[i].CssClass = "Clicked";
ProfileView.ActiveViewIndex = i;
}
else
_tabs[i].CssClass = "Initial";
}
}
我确实进行了调试并试图查看是否调用了 TabClick,但显然它在页面到达之前就崩溃了。如果我注释掉:
ProfileView.ActiveViewIndex = 0;
我可以单击一个选项卡,它会成功切换,但是当单击另一个选项卡时,它会崩溃并出现如下错误:
ActiveViewIndex 被设置为“2”。它必须小于当前视图控件的数量“0”。对于动态添加的视图,请确保在 Page_PreInit 事件之前或中添加它们。
我究竟做错了什么?