复选框检查无效

时间:2015-12-04 08:43:05

标签: c# asp.net gridview checkbox obout

我在gridview中有4-5 checkbox。我想将其值保存到数据库中,如

如果checked == true,则"Y"其他"N"

但是错误

  

对象引用未设置为对象的实例

我将所有复选框定义如下

GridDataControlFieldCell chkcellAdd = GrdRights.RowsInViewState[i].Cells[4] as GridDataControlFieldCell;
GridDataControlFieldCell chkcellView = GrdRights.RowsInViewState[i].Cells[5] as GridDataControlFieldCell;
GridDataControlFieldCell chkcellEdit= GrdRights.RowsInViewState[i].Cells[6] as GridDataControlFieldCell;
GridDataControlFieldCell chkcellDelete = GrdRights.RowsInViewState[i].Cells[7] as GridDataControlFieldCell;

CheckBox chkadd = chkcellAdd.FindControl("ChkIDAdd") as CheckBox;
CheckBox chkview = chkcellView.FindControl("ChkIDView") as CheckBox;
CheckBox chkedit = chkcellEdit.FindControl("ChkIDEdit") as CheckBox;
CheckBox chkdelete = chkcellDelete.FindControl("ChkIDDelete") as CheckBox;

我尝试了here的链接,但收到同样的错误。

请说明这里有什么问题

我的gridview的HTML: -

<cc2:Grid ID="GrdRights" runat="server" FolderStyle="../Styles/Grid/style_12"
    AllowSorting="False" AutoGenerateColumns="False" AllowColumnResizing="true" AllowAddingRecords="false"
    AllowMultiRecordSelection="true" OnRowDataBound="GrdRights_RowDataBound" ViewStateMode="Enabled"
    PageSize="100">
    <ClientSideEvents OnClientSelect="FunMonthList" />
    <ScrollingSettings ScrollHeight="400px" />
    <Columns>
        <cc2:Column ID="Column1" DataField="MKEY" ShowHeader="false" HeaderText="Select" ReadOnly="true"
            Width="5%" runat="server">
            <TemplateSettings TemplateId="TemplateWithCheckbox" />
        </cc2:Column>

        <cc2:Column ID="Column2" DataField="parent_menu" HeaderText="MENU" Visible="true"
            ReadOnly="true" Width="10%" runat="server">
        </cc2:Column>
        <cc2:Column ID="Column4" DataField="child_menu_mkey" Visible="false" ReadOnly="true"
            Width="10%" runat="server">
        </cc2:Column>
        <cc2:Column ID="Column3" DataField="child_menu" HeaderText="SUB MENU" runat="server"
            Visible="true" Width="30%">
        </cc2:Column>

          <%--<cc2:Column ID="Column5" DataField="MKEY" ShowHeader="false" HeaderText="Select"                                                  ReadOnly="true" Width="5%" runat="server">
            <TemplateSettings TemplateId="TemplateWithCheckbox" />
        </cc2:Column>--%>

        <cc2:CheckBoxColumn Id="chkAdd" DataField="ADD_FLAG" ShowHeader="true" HeaderText="Add"
            Width="5%" runat="server" Align="right">
            <TemplateSettings TemplateId="TemplateWithChecAdd"  />
        </cc2:CheckBoxColumn>

        <cc2:CheckBoxColumn Id="chkEdit" DataField="MODIFY_FLAG" ShowHeader="true" HeaderText="Edit"
            Width="5%" runat="server" Align="right">
            <TemplateSettings TemplateId="TemplateWithChecEdit" />
        </cc2:CheckBoxColumn>

        <cc2:CheckBoxColumn Id="ChkView" DataField="VIEW_FLAG" ShowHeader="true" HeaderText="View"
            Width="6%" runat="server" Align="right">
            <TemplateSettings TemplateId="TemplateWithChecView" />
        </cc2:CheckBoxColumn>

        <cc2:CheckBoxColumn Id="ChkDelete" DataField="DEL_FLAG" ShowHeader="true" HeaderText="Delete"
            Width="8%" runat="server" Align="right"> 
            <TemplateSettings TemplateId="TemplateWithChecDelete" />
        </cc2:CheckBoxColumn>

    </Columns>
    <Templates>

        <cc2:GridTemplate ID="TemplateWithChecAdd">
            <Template>
                <asp:CheckBox runat="server" ID="ChkIDAdd" ToolTip="<%# Container.Value %>"  />
            </Template>
        </cc2:GridTemplate>

        <cc2:GridTemplate ID="TemplateWithChecView">
            <Template>
                <asp:CheckBox runat="server" ID="ChkIDView" ToolTip="<%# Container.Value %>" />
            </Template>
        </cc2:GridTemplate>

        <cc2:GridTemplate ID="TemplateWithChecEdit">
            <Template>
                <asp:CheckBox runat="server" ID="ChkIDEdit" ToolTip="<%# Container.Value %>" />
            </Template>
        </cc2:GridTemplate>

        <cc2:GridTemplate ID="TemplateWithChecDelete">
            <Template>
                <asp:CheckBox runat="server" ID="ChkIDDelete" ToolTip="<%# Container.Value %>" />
            </Template>
        </cc2:GridTemplate>

    </Templates>
</cc2:Grid>

更新

根据我的代码现在,我得到了复选框值,但数据没有插入到表中,我收到错误

  

列名&#39; ADD_FLAG&#39;在结果列列表中出现多次。   Msg 264,Level 16,State 1,Line 1

     

列名&#39; MODIFY_FLAG&#39;在结果列列表中出现多次。   Msg 264,Level 16,State 1,Line 1

     

列名&#39; VIEW_FLAG&#39;在结果列列表中出现多次。   Msg 264,Level 16,State 1,Line 1

     

列名&#39; DEL_FLAG&#39;在结果列列表中出现多次。

以下是我的代码: -

public bool Save()
{
    try
    {
        for (int i = 0; i < GrdRights.RowsInViewState.Count; i++)
        {
            string strSQLMKEY = "SELECT WMS_User_Rights.MKEY  FROM WMS_User_Rights Inner JOIN WMS_Menu_Rights on " +
                                       "WMS_User_Rights.User_Id = WMS_Menu_Rights.Mkey " +
                                       "where WMS_User_Rights.User_Id='" + Hid_Selected_user.Value + "' " +
                                       "AND WMS_User_Rights.DELETE_FLAG = 'N'";
            if (GrdRights.Rows[i].Cells[GrdRights.Columns.GetColumnIndexByDataField("child_menu_mkey")].Text.Trim().ToString() == "0")
            {
                strSQLMKEY += " and MENU_MKEY='" + GrdRights.Rows[i].Cells[GrdRights.Columns.GetColumnIndexByDataField("MKEY")].Text.Trim() + "'";
            }
            else
            {
                strSQLMKEY += " and MENU_MKEY='" + GrdRights.Rows[i].Cells[GrdRights.Columns.GetColumnIndexByDataField("child_menu_mkey")].Text.Trim() + "'";
            }
            con.Open();
            SqlCommand cmdMKEY = new SqlCommand(strSQLMKEY, con);
            if (cmdMKEY.ExecuteScalar() != null)
            {
                strMode = "M";
                iMKey = Convert.ToInt32(cmdMKEY.ExecuteScalar());
            }
            else
            {
                strMode = "A";
                iMKey = 0;
            }
            con.Close();
            System.Text.StringBuilder StrPubBldg = new System.Text.StringBuilder();
            XmlWriter xw = XmlWriter.Create(StrPubBldg);
            xw.WriteStartElement("DocumentElement");
            {
                xw.WriteStartElement("WMS_Menu_Rights");
                for (int j = 0; j < GrdRights.RowsInViewState.Count; j++)
                {
                    bool str_checkadd = ((CheckBox)((GridDataControlFieldCell)GrdRights.RowsInViewState[j].Cells[4]).FindControl("ChkIDAdd")).Checked;
                    bool str_checkEdit = ((CheckBox)((GridDataControlFieldCell)GrdRights.RowsInViewState[j].Cells[5]).FindControl("ChkIDEdit")).Checked;
                    bool str_checkView = ((CheckBox)((GridDataControlFieldCell)GrdRights.RowsInViewState[j].Cells[6]).FindControl("ChkIDView")).Checked;
                    bool str_checkdel = ((CheckBox)((GridDataControlFieldCell)GrdRights.RowsInViewState[j].Cells[7]).FindControl("ChkIDDelete")).Checked;

                    xw.WriteElementString("ADD_FLAG", str_checkadd == true ? "Y" : "N");
                    xw.WriteElementString("MODIFY_FLAG", str_checkEdit == true ? "Y" : "N");
                    xw.WriteElementString("VIEW_FLAG", str_checkView == true ? "Y" : "N");
                    xw.WriteElementString("DEL_FLAG", str_checkdel == true ? "Y" : "N");

                    if (GrdRights.Rows[i].Cells[GrdRights.Columns.GetColumnIndexByDataField("child_menu_mkey")].Text.Trim().ToString() == "0")
                    {
                        xw.WriteElementString("MENU_MKEY", GrdRights.Rows[i].Cells[GrdRights.Columns.GetColumnIndexByDataField("MKEY")].Text.Trim());
                    }
                    else
                    {
                        xw.WriteElementString("MENU_MKEY", GrdRights.Rows[i].Cells[GrdRights.Columns.GetColumnIndexByDataField("child_menu_mkey")].Text.Trim());
                    }
                    xw.WriteElementString("USER_ID", Hid_Selected_user.Value);
                    xw.WriteElementString("DELETE_FLAG", "N");
                    xw.WriteElementString("CREATION_DATE", System.DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss"));
                }

                xw.WriteEndElement();
                xw.Close();
                MainEnqMkey = InsertUpdateDelete.InsertUpdateDeleteCls.InsertUpdateDelete_sql(strMode, Convert.ToInt16(iMKey), "WMS_Menu_Rights", "MKEY", "MUR", StrPubBldg.ToString());
            }

        }
        if (MainEnqMkey.Equals(0))
        {
            ClientScript.RegisterStartupScript(this.GetType(), "SuccessScript", "alert('Some Error Occured While Saving Data !!')", true);
        }
        else
        {
            con.Open();
            SqlCommand ObjPriCmd = new SqlCommand("delete from WMS_User_rights where MKEY=" + HidTempMkey.Value, con);
            ObjPriCmd.ExecuteNonQuery();
            con.Close();

            if (!Directory.Exists(Server.MapPath(StrFolder)))
            {
                Directory.CreateDirectory(Server.MapPath(StrFolder));
            }
            if (File.Exists(Server.MapPath(StrFolder + StrFileName)) == false)
            {
                using (System.IO.StreamWriter sw = File.CreateText(Server.MapPath(StrFolder + StrFileName)))
                {
                    sw.WriteLine("\n");

                    sw.WriteLine("\n"); sw.NewLine = "\n------------------------------------------------------------------";
                    sw.WriteLine("\n");
                    sw.Close();
                    sw.Dispose();
                }
            }
            else
            {
                using (System.IO.StreamWriter sw = File.AppendText(Server.MapPath(StrFolder + StrFileName)))
                {

                    sw.WriteLine("\n");

                    sw.WriteLine("\n"); sw.NewLine = "------------------------------------------------------------------";
                    sw.WriteLine("\n");
                    sw.Close();
                    sw.Dispose();
                }
            }
        }
        return true;
    }
    catch (Exception ex)
    {
        if (!Directory.Exists(Server.MapPath(StrFolder)))
        {
            Directory.CreateDirectory(Server.MapPath(StrFolder));
        }
        if (File.Exists(Server.MapPath(StrFolder + StrFileName)) == false)
        {
            using (System.IO.StreamWriter sw = File.CreateText(Server.MapPath(StrFolder + StrFileName)))
            {
                sw.WriteLine("\n");

                sw.WriteLine("\n"); sw.NewLine = "\n------------------------------------------------------------------";
                sw.WriteLine("\n");
                sw.Close();
                sw.Dispose();
            }
        }
        else
        {
            using (System.IO.StreamWriter sw = File.AppendText(Server.MapPath(StrFolder + StrFileName)))
            {

                sw.WriteLine("\n");

                sw.WriteLine("\n"); sw.NewLine = "------------------------------------------------------------------";
                sw.WriteLine("\n");
                sw.Close();
                sw.Dispose();
            }
        }
        return false;
    }

    finally
    {

    }

}

protected void CmdSave_Click(object sender, EventArgs e)
{
    if (Save() == true)
    {
        fillGrid();
        if (strMode == "M")
        {
            ClientScript.RegisterStartupScript(this.GetType(), "CloseScript", "alert('Record Modified Successfully');window.location.href='Frm_User_Rights.aspx?TranType=MUR&Mode=A&Key=0&PView=N&userid=" + Request.QueryString["userid"].ToString() + "';", true);
        }
        else
        {
            ClientScript.RegisterStartupScript(this.GetType(), "CloseScript", "alert('Record Saved Successfully');window.location.href='Frm_User_Rights.aspx?TranType=MUR&Mode=A&Key=0&PView=N&userid=" + Request.QueryString["userid"].ToString() + "';", true);
        }
    }
}

2 个答案:

答案 0 :(得分:1)

每个GridViewRow都包含这些复选框,并且是NamingContainer - 控件,其中ach ID必须是唯一的,因此您需要在每一行上使用FindControl

foreach (GridViewRow row in GrdRights.Rows)
{
    CheckBox chkadd = row.FindControl("ChkIDAdd") as CheckBox;
    CheckBox chkview = row.FindControl("ChkIDView") as CheckBox;
    CheckBox chkedit = row.FindControl("ChkIDEdit") as CheckBox;
    CheckBox chkdelete = row.FindControl("ChkIDDelete") as CheckBox;
    xw.WriteElementString("ADD_FLAG", chkadd.Checked == true ? "Y" : "N");
    xw.WriteElementString("MODIFY_FLAG", chkedit.Checked == true ? "Y" : "N");
    xw.WriteElementString("VIEW_FLAG", chkview.Checked == true ? "Y" : "N");
    xw.WriteElementString("DEL_FLAG", chkdelete.Checked == true ? "Y" : "N");
}

我不熟悉obout Grid,但似乎这适合你:

for (int j = 0; j < GrdRights.RowsInViewState.Count; j++)
{
    bool str_checkadd = ((CheckBox)((GridDataControlFieldCell)GrdRights.RowsInViewState[j].Cells[4]).FindControl("ChkIDAdd")).Checked;
    bool str_checkEdit = ((CheckBox)((GridDataControlFieldCell)GrdRights.RowsInViewState[j].Cells[5]).FindControl("ChkIDEdit")).Checked;
    bool str_checkView = ((CheckBox)((GridDataControlFieldCell)GrdRights.RowsInViewState[j].Cells[6]).FindControl("ChkIDView")).Checked;
    bool str_checkdel = ((CheckBox)((GridDataControlFieldCell)GrdRights.RowsInViewState[j].Cells[7]).FindControl("ChkIDDelete")).Checked;
    // ....
}

<击>

<击>

但即使我不知道这个RowsInViewState,也应该可以使用这个更简单的代码:

for (int j = 0; j < GrdRights.RowsInViewState.Count; j++)
{
    CheckBox checkadd = (CheckBox) GrdRights.RowsInViewState[j].FindControl("ChkIDAdd");
    CheckBox checkEdit = (CheckBox) GrdRights.RowsInViewState[j].FindControl("ChkIDEdit");
    CheckBox chkView = (CheckBox) GrdRights.RowsInViewState[j].FindControl("ChkIDView");
    CheckBox chkDel= (CheckBox) GrdRights.RowsInViewState[j].FindControl("ChkIDDel");
    // ....
}

<击>

答案 1 :(得分:0)

我在网格视图中没有多少经验,但我认为你循环错误的方式..你循环每一行包括标题,所以请检查行是否是数据行然后尝试查找复选框

这里有一些代码,我发现希望这会对你有所帮助

 foreach (GridViewRow row in GridView1.Rows)
{
    if (row.RowType == DataControlRowType.DataRow)
    {
        CheckBox chkRow = (row.Cells[0].FindControl("chkRow") as CheckBox);
        if (chkRow.Checked)
        {
    //your code
        }
    }
}