Re-populating checkboxlist in Edit Mode from SQL comma-separated string is not selecting checkboxes

StackOverflow https://stackoverflow.com/questions/21590285

  •  07-10-2022
  •  | 
  •  

Question

I am not able to pre-populate CheckBoxList3 in my app. I have successfully retrieved string data from database and passed to array but routine fails with:

NullReferenceException:Object not set to instance of an object error at line:
ListItem currentCheckBox = cb3.Items.FindByValue(items[i].ToString());

readMyString() method uses SqlDataReader to read and split a string column from SQL table then pass the values for example: "A, B, C" to string array to identify which of 6 checkboxes should be selected. Code reference: [http://mikesdotnetting.com/Article/53/Saving-a-user's-CheckBoxList-selection-and-re-populating-the-CheckBoxList-from-saved-data]

HTML CODE:

<asp:GridView ID="GridView1" runat="server" 
              AutoGenerateColumns="False" CellPadding="4" DataKeyNames="MyID"   
              DataSourceID="sdsmyTable1" ForeColor="#333333" GridLines="None" 
              onrowdeleted="GridView1_RowDeleted" 
              onrowdeleting="GridView1_RowDeleting" 
              onrowupdated="GridView1_RowUpdated"  
              onrowupdating="GridView1_RowUpdating" 
              onselectedindexchanged="GridView1_SelectedIndexChanged" 
              onrowediting="GridView1_RowEditing" 
              onrowcancelingedit="GridView1_RowCancelingEdit" 
              onrowdatabound="GridView1_RowDataBound">
    <RowStyle BackColor="#EFF3FB" />

    <Columns>
        <asp:CommandField ShowDeleteButton="True" ShowEditButton="True" />

        <asp:BoundField DataField="myID" HeaderText="myID" ReadOnly="True" 
                        SortExpression="myID" />

        <asp:BoundField DataField="Date1" HeaderText="Date driver lic issued" 
                        SortExpression="Date1" />

        <asp:TemplateField HeaderText="chooseOne" SortExpression="chooseOne">
            <ItemTemplate>
                <asp:Label ID="Label1" runat="server" Text='<%# Bind("chooseOne") %>'></asp:Label>
            </ItemTemplate>
            <EditItemTemplate>                
                <asp:RadioButtonList ID="RadioButtonList2" runat="server" SelectedValue='<%# Bind("chooseOne") %>' Font-Size="Small" 
                                     RepeatDirection="Horizontal">
                    <asp:ListItem Value="1">1</asp:ListItem>
                    <asp:ListItem Value="2">2</asp:ListItem>
                    <asp:ListItem Value="3">3</asp:ListItem>
                </asp:RadioButtonList>
            </EditItemTemplate>

        </asp:TemplateField>
        <asp:TemplateField HeaderText="MyCommaSeparatedString" SortExpression="MyCommaSeparatedString">
            <ItemTemplate>
                <asp:Label ID="Label2" runat="server" Text='<%# Bind("MyCommaSeparatedString") %>'></asp:Label>
            </ItemTemplate>
            <EditItemTemplate>
                <asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("MyCommaSeparatedString") %>'></asp:TextBox>
                <asp:CheckBoxList ID="CheckBoxList3" runat="server" Font-Size="Small"  
                                  RepeatDirection="Horizontal">                              
                    <asp:ListItem Value="A">A</asp:ListItem>
                    <asp:ListItem Value="B">B</asp:ListItem>
                    <asp:ListItem Value="C">C</asp:ListItem>                   
                    <asp:ListItem Value="D">D</asp:ListItem>
                    <asp:ListItem Value="E">E</asp:ListItem>
                    <asp:ListItem Value="F">F</asp:ListItem>           
                </asp:CheckBoxList>
            </EditItemTemplate>

C# Code:

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            //// establish a datarow to dig into its minutia
            DataRowView drv = e.Row.DataItem as DataRowView;

            // if 1: RowType of gridview control is a datarow 
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                //if 2: is datarow in edit mode
                if ((e.Row.RowState & DataControlRowState.Edit) > 0)
                {
                  RadioButtonList rb2 = (RadioButtonList)e.Row.FindControl("RadioButtonList2");
                  CheckBoxList cb3 = (CheckBoxList)e.Row.FindControl("CheckBoxList3");
//CheckBoxList cb3 = (CheckBoxList)GridView1.Rows[GridView1.EditIndex].FindControl("CheckBoxList3");
                  CheckBoxList cb4 = (CheckBoxList)e.Row.FindControl("CheckBoxList4");

                    // Create an instance of SqlConn class            
                    SqlConnClass getMyStr= new SqlConnClass();

                    //Return datareader to read Endorsements column from database
                    SqlDataReader rdr = getMyStr.selectMyString(GetMyID());

                    try
                    {
                        // column
                        if (rb2 != null)
                        {
                            rb2.SelectedValue = drv[2].ToString();
                        }

                        // column                    
                        //CheckBoxList cb3 = (CheckBoxList)e.Row.FindControl("CheckBoxList3");
                        if (cb3 != null)//if (cb3 contains 6 checkboxes (I, N, H, X, T, K)
                        {
                            //bind checkbox manually
                            cb3.DataSource = sdsDatasource;
                            cb3.DataTextField = "MyCommaSeparatedString ";
                            cb3.DataValueField = "MyCommaSeparatedString ";
                            cb3.DataBind();

                            // if row exists
                            if (rdr.HasRows)//(dt.Rows.Count > 0 && dt != null)
                            {
                                //start reading
                                rdr.Read();

                //extract comma separated string from datareader into one-dimensional array    
                                string[] items = rdr.GetString(0).Split(',');

               //returns the upper bound for the indexes of the first dimension of the Array
                                for (int i = 0; i <= items.GetUpperBound(0); i++)
                                {
              // currentCheckBox IS WHERE NULL OCCURS: 
              ListItem currentCheckBox = cb3.Items.FindByValue(items[i].ToString());

                                    if (currentCheckBox != null)
                                    {
                                        currentCheckBox.Selected = true;
                                    }
                                    //cb3.SelectedValue = drv[3].ToString();
                                    //}
                                }// end of for

                                //close SqlDataReader
                                rdr.Close();
                            }

                        // column
                        //CheckBoxList cb4 = (CheckBoxList)e.Row.FindControl("CheckBoxList4");
                        if (cb4 != null)
                        {
                            cb4.SelectedValue = drv[4].ToString();
                        }

                        }// end of if
                    }// end of try

                    catch (IndexOutOfRangeException ex2)
                    {
    System.Diagnostics.Debug.WriteLine(ex2.Message + "; " + ex2.Source + "; " + ex2.TargetSite);
                    }//end of catch                
                }// end of if (rowstate)
            } // end of if (rowtype)
        }// end of method

What I have tried: calling readMyString() method from GridView1_RowDataBound event and/or from GridView1_RowEditing event.

Since CheckBoxList3 is empty to begin with and seems to not want to be null, I added the line cb3.Items[i].Value = items[i]; but the error just moves to the new line instead. I must be missing something.

Can anyone see where I've errored? I must be putting the code in the wrong methods...?

Was it helpful?

Solution

You are trying to find the control in the GridView. The controls are inside the GridView Rows. So you need to do something like this:

CheckBoxList cb3 = (CheckBoxList) GridView1.Rows[GridView1.EditIndex].FindControl("CheckBoxList3");

Trim the items[i] like below:

ListItem currentCheckBox = cb3.Items.FindByValue(items[i].Trim());
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top