我正在尝试将转发器生成的控件(复选框,下拉列表,文本框)中的用户选择传递给数据表,并将其用作gridview的数据源进行测试,最后作为表变量用于存储过程参数。
如果某些复选框没有选择,则不会生成相应的文本框,并且代码会抛出异常(check to determine if the object is empty before calling the method
)。
似乎导致问题的部分是当我将文本从texbox传递到数据表时。当我通过复选框名称时,它工作正常;我试图通过检查文本框控件是否生成但仍然引发相同的异常来克服这个问题。
有没有更好的方法来检查是否生成了动态文本框?
protected void Button2_Click(object sender, EventArgs e)
{
DataTable Frs = new DataTable("udtMParameters");
Frs.Columns.Add("MName", typeof(string));
Frs.Columns.Add("IsNum", typeof(string));
Frs.Columns.Add("MValue1", typeof(string));
Frs.Columns.Add("MValue2", typeof(string));
try
{
foreach (RepeaterItem i in Repeater1.Items)
{
CheckBox fn = i.FindControl("chk") as CheckBox;
CheckBox isn = i.FindControl("ChkboxIsNumeric") as CheckBox;
PlaceHolder plc = i.FindControl("PlcMFilter") as PlaceHolder;
TextBox s = i.FindControl("start") as TextBox;
TextBox l = i.FindControl("end") as TextBox;
DropDownList d = i.FindControl("value") as DropDownList;
if (fn.Checked)
{
TextBox1.Text = fn.Text;
if (isn.Checked)
{
DataRow dr = Frs.NewRow();
dr["MName"] = fn.Text;
dr["IsNum"] = "Y";
if (String.IsNullOrEmpty(s.Text))
{
dr["MValue1"] = s.Text;
}
else
{
dr["MValue1"] = " ";
}
if (String.IsNullOrEmpty(s.Text))
{
dr["MValue2"] = l.Text;
}
else
{
dr["MValue2"] = " ";
}
Frs.Rows.Add(dr);
}
else
{
DataRow dr = Frs.NewRow();
dr["MName"] = fn.Text;
dr["IsNum"] = "N";
dr["MValue1"] = "MValue1";
dr["MValue2"] = "MValue2";
Frs.Rows.Add(dr);
}
}
this.GridView1.Visible = true;
GridView1.DataSource = Frs;
GridView1.DataBind();
panel2.Enabled = true;
panel2.Visible = true;
}
}
catch (Exception ex)
{
throw ex;
}
}
答案 0 :(得分:0)
用括号替换你用as实现的转换,以便本地化你的空对象
TextBox s = (TextBox)i.FindControl("start");
TextBox l = (TextBox)i.FindControl("end");
如果转换失败,使用括号进行转换会引发异常,而使用as转换会产生null。