2013-09-24 52 views
0

我動態生成的複選框,這一切都寫在Page_Load中,當我嘗試檢查示值誤差的複選框,如何讓動態CheckBox控件的ID

錯誤行:

CheckBox cb = (CheckBox)Page.FindControl("chk" + j);

錯誤:找到具有相同ID'1'的多個控件。 FindControl需要控件具有唯一的ID

我的要求是:

如果我檢查我想複選框數算的複選框選中和單選按鈕會出現相對選中的複選框。

下面是代碼:

 string strfromdt = Session["leavefrm"].ToString(); 
     DateTime startDate = Convert.ToDateTime(strfromdt); 
     string strtodt = Session["leaveto"].ToString(); 
     DateTime endDate = Convert.ToDateTime(strtodt); 

     string strdays = Session["noofdays"].ToString(); 
     float daysf = float.Parse(strdays); 
     float days = (float)Math.Ceiling(daysf); 
     CheckBox chk; 
     Label lbl; 
     RadioButton rd; 

     days++; 

       OleDbCommand cmd; 
       DbConnection.Open(); 
       cmd = new OleDbCommand("select HOL_DATE from IND_HOLIDAYS", DbConnection); 
       OleDbDataAdapter da = new OleDbDataAdapter(cmd); 
       DataTable dt = new DataTable(); 
       da.Fill(dt); 


       for (int j = 1; j <= days - 1; j++) 
       { 
        while(startDate <= endDate) 
        { 
         for (int i = 0; i <= dt.Rows.Count - 1; i++) 
         { 
          string strdate = dt.Rows[i]["HOL_DATE"].ToString(); 
          DateTime date = Convert.ToDateTime(strdate); 

          if (startDate == date) 

           startDate = startDate.AddDays(1); 
         } 

         if ((startDate.DayOfWeek == DayOfWeek.Saturday) || ((startDate.DayOfWeek == DayOfWeek.Sunday))) 
         { 
          startDate = startDate.AddDays(1); 
          continue; 
         } 
         break; 
        } 


        chk = new CheckBox(); 
        chk.ID = j.ToString(); 
        chk.AutoPostBack = true; 
        // chk.Checked = true; 
        lbl = new Label(); 
        lbl.Text = startDate.ToString("dd/MM/yyyy"); 
        lbl.ID = j.ToString(); 
        PlaceHolder1.Controls.Add(lbl); 
        PlaceHolder1.Controls.Add(chk); 

        PlaceHolder1.Controls.Add(new RadioButton { }); 

        PlaceHolder1.Controls.Add(new LiteralControl("<BR>")); 

        startDate = startDate.AddDays(1); 



        CheckBox cb = (CheckBox)Page.FindControl("chk" + j); 

        //chk.Checked = CheckBox1Checked; 
        //chk.oncheckedchanged += CheckBox1OnChecked; 

        int chkcount = 0; 
        if (chk.Checked) 
        { 
         chkcount++; 
        } 
        int chkcount1 = chkcount; 
       } 

回答

0

你給同一個ID chklbl(均爲j.ToString()),你需要讓他們獨特:

chk.ID = string.Format("chk{0}", j); 
lbl.ID = string.Format("lbl{0}", j); 
// Now you can FindControl: 
CheckBox cb = (CheckBox)Page.FindControl("chk" + j); 
+0

感謝您的回覆...... – appu

+0

我收到複選框ID,但即使我檢查了複選框也ID顯示檢查是錯誤 – appu

+0

您的解決方案正在工作 – appu

0

您需要在OnInit方法中添加動態控件,以便它們在所有情況下都能正常工作。我記得在Page_Load中添加了動態控件的問題。

有一個錯誤RGraham已經指出與相同的ID被添加到不同的控制。

此外,還有這種說法似乎並沒有什麼目的

PlaceHolder1.Controls.Add(新單選按鈕{});