从中继器控件选择的动态创建的文本框中检索文本

本文关键字:文本 检索 创建 动态 中继器 控件 选择 | 更新日期: 2023-09-27 17:59:47

我正试图将用户从中继器生成的控件(复选框、下拉列表、文本框)中选择的内容传递到数据表,并将其用作网格视图的数据源进行测试,最终作为表变量参数传递到存储过程。

如果没有选择某些复选框,则不会生成相应的文本框,并且代码会引发异常(check to determine if the object is empty before calling the method)。

导致问题的部分似乎是当我将文本从文本框传递到数据表时。当我通过复选框名称时,它运行良好;我试图通过检查是否生成了文本框控件来克服这一问题,但它仍然抛出相同的异常。

是否有更好的方法来检查是否生成了动态文本框?

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;
    }
}

从中继器控件选择的动态创建的文本框中检索文本

用括号替换用as实现的强制转换,以便本地化空对象

TextBox s = (TextBox)i.FindControl("start");
TextBox l = (TextBox)i.FindControl("end");

在转换失败的情况下,带括号的强制转换将引发异常,而带as的强制转换会产生null。