访问在C#中动态创建的复选​​框值 [英] Access dynamically created checkbox values in c#

查看:115
本文介绍了访问在C#中动态创建的复选​​框值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我添加了一个复选框动态asp.net中

I have added a CheckBox dynamically in asp.net

CheckBox cb = new CheckBox();
cb.Text = "text";
cb.ID = "1";

我可以在页面加载通过C#访问此复选框本身,略高于codeS宣布之后。
但是,当我尝试按钮后,访问此值,单击我得到空值。

I can access this CheckBox via c# in pageLoad itself, just after declaring above codes. But when I try to access this values after a button click I'm getting null values.

CheckBox cb1 = (CheckBox)ph.FindControl("1");
Response.Write(cb1.Text);
   ph.Controls.Add(cb);

PH 是一个占位符)
任何一个可以告诉我,什么是错在这里?

(ph is a placeholder) Can any one tell me whats wrong here?

推荐答案

在后点击按钮会回来后,这将刷新状态页面。如果你需要的值是持久的,那么你就需要让他们的的ViewState 或内部支持类似。

After you click the button it will post back the page which will refresh the state. If you want the values to be persistent then you'll need to have them backed inside the ViewState or similar.

private bool CheckBox1Checked
{
    get { return (ViewState["CheckBox1Checked"] as bool) ?? false; }
    set { ViewState["CheckBox1Checked"] = value; }
}

void Page_load(object sender, EventArgs e)
{

    CheckBox cb = new CheckBox();
    cb.Text = "text";
    cb.ID = "1";
    cb.Checked = CheckBox1Checked;
    cb.OnCheckedChanged += CheckBox1OnChecked;
    // Add cb to control etc..
}

void CheckBox1OnChecked(object sender, EventArgs e)
{
    var cb = (CheckBox)sender;
    CheckBox1Checked = cb.Checked;
}

这篇关于访问在C#中动态创建的复选​​框值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆