【发布时间】:2015-08-13 02:54:27
【问题描述】:
以下代码显示了一些复选框,如果您选择其中任何一个,它将在页面上列出。
问题是我想在页面上使用"LinkButton",如果我单击链接,则会显示复选框。当我在"asp:LinkButton" 中使用OnLoad="Page_Edit" 时,checkboxlist 工作正常,但我不希望checkboxlist 一直显示,我希望通过单击“单击以使用复选框!”来显示它。关联。如果我使用OnClick="Page_Edit",通过选择任何复选框,checkboxlist 就会消失。任何帮助,将不胜感激。
<h3> CheckBoxList Constructor Example </h3>
<asp:LinkButton id="myid" runat="server" Text="Click to work with checkbox!" OnLoad="Page_Edit" OnClick="Page_Edit" /><br />
Select items from the CheckBoxList.
<br /><br />
<asp:PlaceHolder id="Place" runat="server"/>
<br /><br />
<asp:label id="Message" runat="server"/>
void Check_Clicked(对象发送者,EventArgs e) {
// Retrieve the CheckBoxList control from the Controls collection
// of the PlaceHolder control.
CheckBoxList checklist = (CheckBoxList)Place.FindControl("checkboxlist1");
// Make sure a control was found.
if(checklist != null)
{
Message.Text = "Selected Item(s):<br /><br />";
// Iterate through the Items collection of the CheckBoxList
// control and display the selected items.
for (int i=0; i<checklist.Items.Count; i++)
{
if (checklist.Items[i].Selected)
{
Message.Text += checklist.Items[i].Text + "<br />";
}
}
}
else
{
// Display an error message.
Message.Text = "Unable to find CheckBoxList control.";
}
}
void Page_Edit(Object sender, EventArgs e)
{
// Create a new CheckBoxList control.
CheckBoxList checklist = new CheckBoxList();
// Set the properties of the control.
checklist.ID = "checkboxlist1";
checklist.AutoPostBack = true;
checklist.CellPadding = 5;
checklist.CellSpacing = 5;
checklist.RepeatColumns = 2;
checklist.RepeatDirection = RepeatDirection.Vertical;
checklist.RepeatLayout = RepeatLayout.Flow;
checklist.TextAlign = TextAlign.Right;
// Populate the CheckBoxList control.
checklist.Items.Add(new ListItem("Item 1"));
checklist.Items.Add(new ListItem("Item 2"));
checklist.Items.Add(new ListItem("Item 3"));
checklist.Items.Add(new ListItem("Item 4"));
checklist.Items.Add(new ListItem("Item 5"));
checklist.Items.Add(new ListItem("Item 6"));
// Manually register the event-handling method for the
// SelectedIndexChanged event.
checklist.SelectedIndexChanged += new EventHandler(this.Check_Clicked);
// Add the control to the Controls collection of the
// PlaceHolder control.
Place.Controls.Add(checklist);
}
【问题讨论】:
-
我无法准确理解您希望代码做什么。您能否指定预期的行为是什么以及它与您现在的行为有何不同?
-
可能使用客户端脚本会是一个更好、更简单的选择,因为您不需要通过服务器调用来显示和隐藏 dom 元素。
-
我在页面上有一个“单击以使用复选框”链接,如果我单击它,必须显示几个复选框,如果我选择其中任何一个,复选框的名称将出现在页也。现在我的代码可以一直显示这个复选框,而不仅仅是当我点击链接时。第二个问题是,当我可以在“linkbutton”上使用“onclick=Page-Edit”以我想要的方式工作时,如果我选择其中一个复选框,它会使复选框列表消失。
标签: c# asp.net checkboxlist asplinkbutton