private void createnewTable(int ts,int sid)
{
SubjectClass s1 = new SubjectClass();
List<string> sub = new List<string>();
sub = s1.returnSubjectList(sid);
Table timetable = new Table();
int height = 20;
Panel1.Attributes.Add("style", "height:" + height.ToString() + "px;");
for (int i = 1; i <= ts; i++)
{
height = height + 20;
TableRow tr = new TableRow();
TableCell td1 = new TableCell();
Label lbl = new Label();
lbl.Text = "Lecture" + (i).ToString();
td1.Controls.Add(lbl);
tr.Controls.Add(td1);
for (int j = 1; j <= 6; j++)
{
TableCell td2 = new TableCell();
DropDownList drop_sub = new DropDownList();
drop_sub.ID = "drop" + i.ToString() + j.ToString();
foreach (string s in sub)
{
drop_sub.Items.Add(s.ToString());
}
drop_sub.Items.Add("No lecture");
td2.Controls.Add(drop_sub);
tr.Controls.Add(td2);
Panel1.Attributes.Add("style", "height:" + height.ToString() + "px;");
}
timetable.Controls.Add(tr);
}
panel_timetable.Controls.Add(timetable);
}
protected void btn_save_Click(object sender, EventArgs e)
{
int totsub = int.Parse(Session["ts"].ToString());
Session["ts"] = null;
List<string> sub = new List<string>();
for (int i = 1; i <= totsub; i++)
{
for (int j = 1; j <= 6; j++)
{
DropDownList drop = new DropDownList();
drop = (DropDownList)(panel_timetable.FindControl("drop"+i.ToString()+j.ToString()));//here error that Object reference //not set to an instance of an object.
string str = drop.SelectedValue;
sub.Add(str);
}
}
}
在上面的代码中,我想创建一个具有多个DropDownList控件的新表,并在按钮点击保存时,我想将填充数据保存在下拉列表中。在FindControl中,它显示一个错误,即Object引用未设置为对象的实例。
答案 0 :(得分:0)
您遇到此错误,因为动态创建的控件在回发后会刷新。
您需要重新创建它们才能使它们可用,或者您可以使用其他方式。
例如,在按钮点击时从javascript访问下拉列表并在js中使用它。您可以将其结果存储在隐藏字段中,该字段将在后面的代码中可用。
检查此链接: http://www.learning2code.net/Learn/2009/8/12/Adding-Controls-to-an-ASPNET-form-Dynamically.aspx