2012-10-24 87 views
0

從我的previous post我使用JavaScript來檢查一些工作正常的複選框。但是,我有一個按鈕,將一些記錄放入數據庫中。使用下面的代碼,是否選中複選框並不重要,它總是讓我錯誤。無法讀取GridView中的複選框

 bool first = true; 
     bool _IsPhone = false; 
     bool _IsLotus = false; 
     bool _IsRelationship = false; 
     bool _IsAdmin = false; 
     string _Country; 

     foreach (GridViewRow row in CountryAccessGrid.Rows) 
     { 
      CheckBox ch = ((CheckBox)row.FindControl("chkPhones")); 

      _Country = ((Label)row.FindControl("lblCountryShort")).Text; 
      _IsPhone = ((CheckBox)row.FindControl("chkPhones")).Checked; 
      _IsLotus = ((CheckBox)row.FindControl("chkLotus")).Checked; 
      _IsRelationship = ((CheckBox)row.FindControl("chkRelationship")).Checked; 
      _IsAdmin = ((CheckBox)row.FindControl("chkIsAdmin")).Checked; 

      if (_IsPhone == true || _IsLotus == true || _IsRelationship == true || _IsRelationship == true || _IsAdmin == true) 
      { 
       cntr = cntr + 1; 

       if (!first) 
       { 
        insertaccess += " UNION ALL "; 
       } 
       insertaccess += " SELECT " + _UserID + ", '" + _Country + "', " + _IsPhone + ", " + _IsLotus + ", " + _IsRelationship + ", " + _IsAdmin; 

       first = false; 
      } 
     } 

如何獲取複選框的狀態?

+0

從哪裏是這樣的代碼,什麼是數據源,以及如何/你什麼時候數據綁定它到GridView? –

回答

0

爲了能夠asnwer這個問題,我們必須知道以下幾點:

  • 從那裏是這個代碼
  • 什麼DataSource
  • 這裏/你是DataBindGridView什麼時候?

但我認爲你總是DataBind它在Page_Load即使它是回發。這將覆蓋這些值並防止事件被觸發。

所以,你必須使用IsPostBack屬性:

private void Page_Load() 
{ 
    if (!IsPostBack) 
    { 
     DataBindGridView(); 
    } 
} 
+0

是的,情況就是這樣。謝謝! – jambis

0

我suggets你使用RowDataBound event

void GridView_RowDataBound(Object sender, GridViewRowEventArgs e) 
{ 
    if(e.Row.RowType == DataControlRowType.DataRow) 
    { 
     var ch = (CheckBox)row.FindControl("chkPhones"); 
    } 
    } 

<asp:gridview id="GridView" onrowdatabound="GridView_RowDataBound" runat="server"> 
     </asp:gridview>