从表中选择“DYNAMIC”下拉列表项

时间:2011-06-07 20:52:45

标签: c# asp.net drop-down-menu tablecell

// Code BehindFile

public void Button1_Click(object sender, EventArgs e)
 {
             while (reader.Read())
         {

            DropDownList ddl = new DropDownList();
             string[] s = { "Present", "Absent1", "Absent2", "Absent3" };
             for (int i = 0; i < 3; i++)
             {
                 ddl.Items.Add(s[i]);
             }
             ddl.ID = "ddl";
             TableCell c2 = new TableCell();
             c2.Controls.Add(ddl);
             r.Cells.Add(c2);
             Table1.Rows.Add(r);
            }
 }

 public void Button2_Click1(object sender, EventArgs e)

 {

         foreach (TableRow tr in Table1.Controls)
         {
             foreach (TableCell tc in tr.Controls)
             {
                 if (tc.Controls[2] is DropDownList)
                {
                 Response.Write(((DropDownList)tc.Controls[2]).SelectedItem.Text+" ");
                }
             }
             Response.Write("<br/>");
         }

问题在于选择下拉列表项目。我无法打印相应的选定项目值。有人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

当你在最后一个嵌套的foreach中时检查tc.Controls [2]。您的下拉列表是否可能不是第三个控件?

我认为没有任何理由会强迫它成为该Cell中的第三个控件。

你最好做这样的事情:

if(tc.FindControl("ddl") != null)
{
   Response.Write(((DropDownList)tc.FindControl("ddl")).SelectedItem.Text+" ");
}

而不是:

 if (tc.Controls[2] is DropDownList)
 {
    Response.Write(((DropDownList)tc.Controls[0]).SelectedItem.Text+" ");
 }