C#获取动态生成的CheckBox值
来源:本站原创|时间:2022-11-25|栏目:C#教程|
给你推荐两种方法,一种是向服务器容器控件里添加子控件(即向runat=server的控件的Controls里添加控件),第二种是就是你的这种拼接HTML的方法不过这种方法必须设置控件的name属性,然后在Request.Form["控件的name"]里获得控件的值,推荐使用第一种方法,更直观一些,第二种无法记录提交以后的状态,代码如下
第一种
后台
using System.Web.UI.HtmlControls; protected void Page_Load(object sender, EventArgs e) { for (int i = 0; i < 4; i++) { HtmlInputCheckBox htmlInputCheckBox = new HtmlInputCheckBox();//这里用CheckBox也是一样的 htmlInputCheckBox.ID = "check" + i; Container.Controls.Add(htmlInputCheckBox); } } protected void Button1_Click(object sender, EventArgs e) { for (int i = 0; i < 4; i++) { Label1.Text += "<br/>" + (Container.FindControl("check" + i) as HtmlInputCheckBox).Checked.ToString(); } }
前台
<form id="form1" runat="server"> <div id="Container" runat="server"> </div> <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" /> <asp:Label ID="Label1" runat="server"></asp:Label> </form>
第二种
后台
public string GetCheckBox() { return "<input name=\"Checkbox1\" type=\"checkbox\"/>";//这里必须设置name,Id没有用 } protected void Button1_Click(object sender, EventArgs e) { if (Request.Form["Checkbox1"] == null)//如果Checkbox1为未选中状态Request.Form["Checkbox1"]值为null { Label1.Text += "<br/>Fasle"; } else//如果Checkbox1为选中状态Request.Form["Checkbox1"]值为on { Label1.Text += "<br/>True"; } }
前台
<form id="form1" runat="server"> <div> <%=GetCheckBox() %> </div> <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" /> <asp:Label ID="Label1" runat="server"></asp:Label> </form>
您可能感兴趣的文章
- 01-10C#通过反射获取当前工程中所有窗体并打开的方法
- 01-10C#获取进程或线程相关信息的方法
- 01-10C#动态创建button的方法
- 01-10C#调用dos窗口获取相关信息的方法
- 01-10C#编程获取资源文件中图片的方法
- 01-10C#获取任务栏显示进程的方法
- 01-10C#动态创建Access数据库及密码的方法
- 01-10C#及WPF获取本机所有字体和颜色的方法
- 01-10C#中DataGridView动态添加行及添加列的方法
- 01-10C#获取网页源代码的方法