2012-10-24 55 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>