遍历一张桌子,我的代码出了什么问题?

时间:2010-09-04 04:48:15

标签: c#

 public partial class Table_Traversing : System.Web.UI.Page
 {
 Table table1 = new Table();


 TableRow table_row1 = new TableRow();

 TableCell table_cell1 = new TableCell();

 TableCell table_cell2 = new TableCell();

 Label The_text = new Label();

 CheckBox checkmate = new CheckBox();

 Button button1 = new Button();



 public void Page_Init(object sender, EventArgs e)
 {
     //Table asdasd = new Table();
 }


 protected void Page_Load(object sender, EventArgs e)
 {


    The_text.Text = "This is the text :-)";

    checkmate.Checked = false;

    table_cell2.Controls.Add(checkmate);

    table_cell1.Controls.Add(The_text);

    table_row1.Controls.AddAt(0, table_cell1);

    table_row1.Controls.AddAt(1, table_cell2);

    table1.Rows.Add(table_row1);


    button1.Text = "click me to export the value";

    form1.Controls.AddAt(0, table1);
    form1.Controls.AddAt(0, button1);


    CheckBox check_or_not = new CheckBox();

    check_or_not = (CheckBox)table1.FindControl("checkmate");

    Response.Write(check_or_not.Checked.ToString());


    button1.Click += new EventHandler(button1_Click);





 }

错误是

对象引用未设置为对象的实例。

异常详细信息:System.NullReferenceException:未将对象引用设置为对象的实例。

来源错误:

第59行:check_or_not =(CheckBox)table1.FindControl(“checkmate”);

第60行:

第61行:Response.Write(check_or_not.Checked.ToString());

第62行:

1 个答案:

答案 0 :(得分:2)

如果你想使用FindControl,你必须给控件一个ID ...所以你必须在调用FindControl之前添加它:

checkmate.ID = "checkmate";