0

I have 4-5 checkbox inside gridview. I want to save its value into the database like,

If checked == true, then "Y" else "N"

but got error as

object reference not set to an instance of an object

I defined all checkboxes as below

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;

I tried a link from here but getting the same error.

Please suggest what is wrong here

HTML of my gridview:-

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

UPDATE

AS per my code now, I got the checkbox values, but the data is not getting inserted into the table and i am getting error as

Column name 'ADD_FLAG' appears more than once in the result column list. Msg 264, Level 16, State 1, Line 1

Column name 'MODIFY_FLAG' appears more than once in the result column list. Msg 264, Level 16, State 1, Line 1

Column name 'VIEW_FLAG' appears more than once in the result column list. Msg 264, Level 16, State 1, Line 1

Column name 'DEL_FLAG' appears more than once in the result column list.

Below is my code:-

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);
        }
    }
}
Community
  • 1
  • 1
Nad
  • 4,605
  • 11
  • 71
  • 160
  • Have you tried adding ClientIDMode="Static" to your checkboxes? – n1FF Dec 04 '15 at 08:47
  • @RahulSingh: i got one thing here, **To the checkbox which i am not checking for that, I am getting the mentioned error** why ?? – Nad Dec 04 '15 at 08:49
  • 1
    **object reference not set to an instance of an object** This error means that the object is null, either set a default value of the checkbox or handle the possibility of it being `null` – hjardine Dec 04 '15 at 08:53

2 Answers2

1

Every GridViewRow contains these checkboxes and is their NamingContainer-control where ach ID must be unique, so you need to use FindControl on each row:

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

I'm not familiar with the obout Grid, but it seems that this works for you:

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

But even with this RowsInViewState which i don't know, it should be possible to use this much simpler code:

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");
    // ....
}

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • @coder: is already `row.FindControl("ChkIDAdd")` `null` or does only the try-cast fail? Inspect the value and (if it's not `null`) the type of `row.FindControl("ChkIDAdd")` in the debugger. – Tim Schmelter Dec 04 '15 at 09:16
  • What kind of `GridView` is this? It's not the standard ASP.NET `GridView`-control. Where is this code located, in which event do you use it? What is `RowsInViewState`? – Tim Schmelter Dec 04 '15 at 09:17
  • @coder: i dont know `RowsInViewState` and why you need that. I'm not familiar with obout grid, maybe it's an issue with it. – Tim Schmelter Dec 04 '15 at 09:44
  • @coder: you haven't edited your question to include your code. But that error is thrown if your sql query contains the same column name multiple times. For example: `SELECT t1.Col1, t1.Col2, t2.Col1 ...` – Tim Schmelter Dec 04 '15 at 11:04
  • @coder: no, use the debugger and look at your generated SQL. However, now it seems that you've fixed your original issue of this question. Try to not ask follow up questions since then the question is not helpful anymore for future readers. – Tim Schmelter Dec 04 '15 at 11:53
  • @coder: updated. However, try to use `GrdRights.RowsInViewState[j].FindControl("ChkIDAdd")` since normally the row is the `NamingContainer`. Then your code is simpler. – Tim Schmelter Dec 04 '15 at 12:00
  • marked as answer, just a suggestion..what may be giving this `column name appears issue` ? is it due to placing of code ?? Also given +1 for clean and clear code. – Nad Dec 04 '15 at 12:02
  • @coder: at which line exactly does the error happen and what sql is generated, use the debugger. If you ask another question show only the relevant code and provide all necessary informations. Often you find the reason for the error yourself by asking a good question that contains all informations. Btw, does my last approach work(edited my answer)? – Tim Schmelter Dec 04 '15 at 12:09
  • I didn't gave your code a try, but for that multiple type issue, i am asking a new question for it – Nad Dec 04 '15 at 12:13
  • I tried your way too but it didn't worked. – Nad Dec 04 '15 at 12:35
  • @coder: then obout grid behaves differently – Tim Schmelter Dec 04 '15 at 12:39
  • yes, maybe. I m too much irritated also with this. As if it was standard `ASP.NET` gridview. I would have completed this task long back. Anyways, thanks for your patience and time – Nad Dec 04 '15 at 12:51
0

well i am not much experienced in grid-view, but i think you are looping it wrong way..you are looping every row including header, so please check if the row is data-row then try to find check-boxes

here is some CODE i found hope this will help you

 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
        }
    }
}
KanisXXX
  • 757
  • 7
  • 19