[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 428
  • Last Modified:

Can't automatically select a databound checkboxListItem

Hi,

I have a databound CheckBoxList (see below)

<asp:CheckBoxList ID="chkBoxSchemes" DataTextField="SchemeRef" DataValueField="SchemeRef" RepeatLayout="Flow" CssClass="LabelBox" runat="server"></asp:CheckBoxList>

And I can't get the items to preselect according to the data that's returned.
Two checkboxs should be checked but none are yet I can see they exist in both the recordset and the list. Can someone help me with the code below please?

Thanks in advance. Chris.

DbMethods db = new DbMethods();
string sql = "SELECT * FROM campaignSchemes WHERE CampaignCode='" + gc.CampaignCode.cValue + "'";
DataSet ds = db.getDataSet(sql);
int rowCount = ds.Tables[0].Rows.Count;
string thisScheme = "";

if (rowCount > 0)
{
      for(int i = 0; i < rowCount; i++)
      {
            thisScheme = ds.Tables[0].Rows[i]["SchemeRef"].ToString();
            ListItem currentCheckBox = this.chkBoxSchemes.Items.FindByValue(thisScheme);
            if (currentCheckBox != null)
            {
                  currentCheckBox.Selected = true;
            }

      }
}
0
w3digital
Asked:
w3digital
  • 4
  • 4
1 Solution
 
Justin_WCommented:
I think the problem is probably that your code is running before the CBList is databound, so when the code runs, the CBList is empty. If you place your code so that it runs _after_ the CBList is databound and populated with items, it should work.
0
 
w3digitalAuthor Commented:
Thanks, I believe it is running after it is databound.

Here's more of the code, thanks.

GlobalCampaigns gc = new GlobalCampaigns(CampaignID);

DataView dv = new Scheme().GetAll().Tables[0].DefaultView;
chkBoxSchemes.DataSource = dv;
chkBoxSchemes.DataBind();

// Get a dataset of current schemes against this campaign code
DbMethods db = new DbMethods();
string sql = "SELECT * FROM campaignSchemes WHERE CampaignCode='" + gc.CampaignCode.cValue + "'";
DataSet ds = db.getDataSet(sql);
int rowCount = ds.Tables[0].Rows.Count; //starting value
string thisScheme = "";

if (rowCount > 0)
{
      for(int i = 0; i < rowCount; i++)
      {
            thisScheme = ds.Tables[0].Rows[i]["SchemeRef"].ToString();
            ListItem currentCheckBox = this.chkBoxSchemes.Items.FindByValue(thisScheme);
            if (currentCheckBox != null)
            {
                  currentCheckBox.Selected = true;
            }

      }
}
0
 
Justin_WCommented:
From the code above, it looks like the only thing that could explain the behavior you described is that either:

1. "thisScheme = ds.Tables[0].Rows[i]["SchemeRef"].ToString();" isn't returning what you expected.

or

2. the Values of the CBList's items aren't what you expected, and is returning null.

Either way, "this.chkBoxSchemes.Items.FindByValue(thisScheme);" would return null and would explain the behavior.

Have you looped through and printed out the values of all of the "ds.Tables[0].Rows[i]["SchemeRef"].ToString();" values and all of the values and texts of all of the items in your CBList after databinding?

If you are actually reaching and executing the "currentCheckBox.Selected = true;" the expected number of times, but the items aren't selected, then I suspect that your CBList might be getting databound again after your selection loop code. Try modifying this code:
    chkBoxSchemes.DataSource = dv;
    chkBoxSchemes.DataBind();
to this:
    chkBoxSchemes.DataSource = dv;
    chkBoxSchemes.DataBind();
    chkBoxSchemes.DataSource = null;
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
w3digitalAuthor Commented:
OK, thanks.

I am stumped as I did output the results to the screen and they do look fine:

The CheckListBox produces this for the value and text:

GASI
PLUM
ELEC
HEAT

The Response.Write to the screen says:

thisScheme = ELEC
thisScheme = HEAT

So they definately exist. The code that out put the response.write is directly above the code to make the listbox selected... most strange.

GlobalCampaigns gc = new GlobalCampaigns(CampaignID);

DataView dv = new Scheme().GetAll().Tables[0].DefaultView;
chkBoxSchemes.DataSource = dv;
chkBoxSchemes.DataBind();
chkBoxSchemes.DataSource = null;

// Pre-check the Schemes Checkbox list

// Get a dataset of current schemes against this campaign code
DbMethods db = new DbMethods();
string sql = "SELECT * FROM campaignSchemes WHERE CampaignCode='" + gc.CampaignCode.cValue + "'";
//Response.Write(sql);
DataSet ds = db.getDataSet(sql);
int rowCount = ds.Tables[0].Rows.Count; //starting value
string thisScheme = "";

if (rowCount > 0)
{
      for(int i = 0; i < rowCount; i++)
      {
            thisScheme = ds.Tables[0].Rows[i]["SchemeRef"].ToString();
            Response.Write("<br>thisScheme = " + thisScheme);
            ListItem currentCheckBox = this.chkBoxSchemes.Items.FindByValue(thisScheme);
            if (currentCheckBox != null)
            {
                  currentCheckBox.Selected = true;
            }

      }
0
 
w3digitalAuthor Commented:
OK, I've narrowed down the problem significantly so it should be easy for you clever people to tell me where I'm going wrong.

As a test I've removed the 'databind' and created the list manually:

<asp:CheckBoxList ID="chkBoxSchemes" RepeatLayout="Flow" CssClass="LabelBox" runat="server">
<asp:ListItem Value="GASI">Gas</asp:ListItem>
<asp:ListItem Value="PLUM">Plumbing</asp:ListItem>
<asp:ListItem Value="ELEC">Electrical</asp:ListItem>
<asp:ListItem Value="VENT">Heating/Ventilation</asp:ListItem>
</asp:CheckBoxList>

This all works fine andn the checkboxes are selected, however using the databound version they are not.

So I guess it's some kind of problem in the way I have databound the chkboxlist? I must be doing something fundamentally wrong as it displays fine but doesn't pre select the boxes.

Here's the code I used.

// Front end
<asp:CheckBoxList ID="chkBoxSchemes" DataTextField="SchemeDescription" DataValueField="SchemeRef" RepeatLayout="Flow" CssClass="LabelBox" runat="server"></asp:CheckBoxList>

// BACK END
DataView dv = new Scheme().GetAll().Tables[0].DefaultView;
chkBoxSchemes.DataSource = dv;
chkBoxSchemes.DataBind();
chkBoxSchemes.DataSource = null

// The rest is as shown above.

The "DataView dv = new Scheme().GetAll().Tables[0].DefaultView;" produces a recordset as follows

ID      SchemeDescription     SchemeRef
1        Gas Installers            GASI
2        Electricians               ELEC

So these should be pre selected and are with the manual approach (which is no good for me) but not with the databound approach (which I need).

Any help would be much appreciated.

Cheers,

Chris.
0
 
Justin_WCommented:
Chris,

You didn't answer about whether the following line returns null when you use DataBind():
   ListItem currentCheckBox = this.chkBoxSchemes.Items.FindByValue(thisScheme);

This is critical info to determining the problem.

Also, your recent comments don't clarify for certain whether the values you are comparing are identical, because some might have leading or trailing whitespace differences.

Please run a test like the following, and post the exact and complete ouput:

if (rowCount > 0)
{
     for(int i = 0; i < this.chkBoxSchemes.Items.Count; i++)
     {
          Response.Write("<br>i = '" + i + "'");
          ListItem currentCheckBox = this.chkBoxSchemes.Items[i];
          if (currentCheckBox != null)
          {
               Response.Write("<br>currentCheckBox.Value = '" + currentCheckBox.Value + "'");
               Response.Write("<br>currentCheckBox.Text = '" + currentCheckBox.Text + "'");
          }
      }
     for(int i = 0; i < rowCount; i++)
     {
          Response.Write("<br>i = '" + i + "'");
          thisScheme = ds.Tables[0].Rows[i]["SchemeRef"].ToString();
          Response.Write("<br>thisScheme = '" + thisScheme + "'");
          ListItem currentCheckBox = this.chkBoxSchemes.Items.FindByValue(thisScheme);
          if (currentCheckBox != null)
          {
               Response.Write("<br>currentCheckBox.Value = '" + currentCheckBox.Value + "'");
               Response.Write("<br>currentCheckBox.Text = '" + currentCheckBox.Text + "'");
               currentCheckBox.Selected = true;
          }

     }
0
 
w3digitalAuthor Commented:
Although I did loop through and print out the results they did APPEAR to be OK.

The problem only made itself apparent when I viewed the 'source'. I was using 4 digit codes but the database was set up as a CHAR (5) and was therefore adding 1 character of white space that I could not see when I looped through the results but could see directly in the source (of course the white space was undetectable on-screen).

Thanks for your help. The mystery is finally resolved.

All the best,

Chris.
0
 
Justin_WCommented:
I thought that might be the case. That's why I added apostrophes in all of the Response.Write() lines in my code above. :)

Cheers.
0

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

  • 4
  • 4
Tackle projects and never again get stuck behind a technical roadblock.
Join Now