无法读取GridView中的复选框

时间:2012-10-24 13:30:12

标签: c# gridview checkbox

从我的previous post我使用javascript检查一些工作正常的复选框。但后来我有一个按钮,将一些记录放在数据库中。使用以下代码,无论是否选中复选框都无关紧要,它总是给我错误。

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

如何获取复选框的状态?

2 个答案:

答案 0 :(得分:0)

为了能够回答这个问题,我们必须知道以下内容:

  • 此代码在哪里
  • 什么是DataSource
  • 您在何时/何时DataBind将其发送到GridView

但我认为你总是DataBind Page_Load即使它是一个回发。这将覆盖值并阻止事件被触发。

所以你必须使用IsPostBack属性:

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

答案 1 :(得分:0)

我建议您使用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>