0

我正在稍微改变 ASP.Net 网站中页面的功能。在原始页面中有一个复选框列表写入页面,没有硬编码的项目。

相反,在初始渲染时,cbl 将数据绑定到查询结果,因此:

sSQL = "select query here";

using (SqlConnection dbcon = new DataAccess().OpenDb())
{
     using (SqlDataReader dr = new SqlCommand(sSQL, dbcon).ExecuteReader())
     {
          cbl.DataTextField = "description";
          cbl.DataValueField = "productid";
          cbl.DataSource = dr;
          cbl.DataBind();
     }
     dbcon.Close();
}

在回发以下代码:

foreach (ListItem li in cbl.Items) { if (li.Selected) rtnQS += li.Value + ","; }

愉快地浏览复选框列表中的动态数据绑定列表项并检索选中的值。我尝试做同样的事情,在页面上放置一个空表,然后动态创建行:

sSQL = "similar select query here";

using (SqlConnection dbcon = new DataAccess().OpenDb())
{
    using (SqlDataReader dr = new SqlCommand(sSQL, dbcon).ExecuteReader())
    {
       while (dr.Read())
       {
           TableRow tr = new TableRow();

           TableCell tc = new TableCell();

           CheckBox chk = new CheckBox();

           chk.Text = dr["description"].ToString();
           chk.InputAttributes.Add("id", dr["id"].ToString());
           chk.Checked = true;

           tc.Controls.Add(chk);

           TableCell tc2 = new TableCell();

           if (Convert.ToBoolean(dr["controlcondition"]))
           {
                CheckBoxList cbl_sub = new CheckBoxList();
                cbl_sub.Attributes.Add("for", dr["id"].ToString());
                sSQL = "subquery";
                using (SqlConnection newcon = new DataAccess().OpenDb())
                {
                   using (SqlDataReader br = new SqlCommand(sSQL, newcon).ExecuteReader())
                   {
                       cbl_block.DataTextField = "subname";
                       cbl_block.DataValueField = "subid";
                       cbl_block.DataSource = br;
                       cbl_block.DataBind();
                   }
                }

                tc2.Controls.Add(cbl_sub);
           }
           else
           {
              TextBox txtSub = new TextBox();
              txtSub.Attributes.Add("for", dr["id"].ToString());

              tc2.Controls.Add(txtSub);
           }

           tr.Cells.Add(tc);
           tr.Cells.Add(tc2);

           tblDispatchOpt.Rows.Add(tr);
        }
    }

    dbcon.Close();
}

唯一的问题是,当迭代器来到表时,它只读取硬编码的标题行。(不过,该表格在原始页面上的所有正确属性都呈现得很漂亮。)

这是尝试读取表行的代码:

foreach (TableRow row in tblDispatchOpt.Rows)
{
      TableCell cell = row.Cells[0];

      ++counter;

      foreach (Control c in cell.Controls)
      {
           if (c is CheckBox)
           {
               CheckBox cb = (CheckBox)c;
               if (cb.Checked && cb.Attributes["ttid"] != null) dtTTInfo.Rows.Add(cb.Attributes["ttid"].ToString(), "", "");
           }
      }
}

除了调试标签检查很高兴地告诉我只有一行而且它是硬编码的标题行。所以基本上不会读取其他行,因为在读取它们时页面似乎不相信它们存在。

那么为什么它不能与桌子一起使用呢?或者,如果它不能与表格一起使用,通常原因是事情不适用于回发的动态控件,例如渲染、生命周期等,为什么它可以与复选框列表一起使用?

4

1 回答 1

1

如果要从中获取值,则必须在每次回发时重新创建动态控件。您应该在 CreateChildControls() 方法中执行此操作。

于 2011-04-06T11:35:15.790 回答