2013-02-15 75 views
1

我試圖從由中繼器所生成的控件(複選框,下拉列表,文本框)的用戶選擇傳遞到一個數據表並使用它作爲一個數據源以用於測試一個gridview並最終作爲表變量參數存儲到存儲過程中。檢索從動態創建texboxes文本

當存在一些沒有複選框選擇,不產生相應的文本框和代碼拋出異常(check to determine if the object is empty before calling the method)。

,這似乎是導致該問題的部分是當我通過從texboxes到數據表中的文本。當我通過複選框名稱它工作正常;我試圖通過檢查是否生成文本框控件來克服這一點,但它仍然會拋出相同的異常。

是否有更好的方法來檢查是否產生動態文本框?

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

歡迎堆棧溢出!請包括您得到的異常的詳細信息,以及代碼中的哪一行會引發異常。這將有助於人們幫助你。您可以使用問題下方的[編輯]鏈接添加該信息。謝謝,祝你好運! – jadarnel27 2013-02-15 17:04:16

+0

我做更多的研究我的問題,發現問題是動態創建控件沒有在郵局後面保留,我需要在頁面加載重建他們,但我仍然不知道如何保持用戶選擇在這些文本框和將它們傳遞給數據表。 – user1721546 2013-02-19 17:14:29

+0

一旦你重新創建它們,這些控件就會保持自己。 – 2013-02-19 17:17:20

回答

0

代替你鑄造與實現爲由括號,以本地化空對象

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

在一個轉換失敗的情況下,用括號鑄造將拋出一個異常,而有作爲的意志鑄造產生一個空值。