Solved

Can't automatically select a databound checkboxListItem

Posted on 2006-07-20
8
416 Views
Last Modified: 2012-05-05
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
Comment
Question by:w3digital
  • 4
  • 4
8 Comments
 
LVL 24

Expert Comment

by:Justin_W
ID: 17150776
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
 

Author Comment

by:w3digital
ID: 17150856
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
 
LVL 24

Accepted Solution

by:
Justin_W earned 500 total points
ID: 17150891
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
 

Author Comment

by:w3digital
ID: 17151082
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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 

Author Comment

by:w3digital
ID: 17152337
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
 
LVL 24

Expert Comment

by:Justin_W
ID: 17155393
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
 

Author Comment

by:w3digital
ID: 17156465
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
 
LVL 24

Expert Comment

by:Justin_W
ID: 17156484
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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In .NET 2.0, Microsoft introduced the Web Site.  This was the default way to create a web Project in Visual Studio 2005.  In Visual Studio 2008, the Web Application has been restored as the default web Project in Visual Studio/.NET 3.x The Web Si…
A quick way to get a menu to work on our website, is using the Menu control and assign it to a web.sitemap using SiteMapDataSource. Example of web.sitemap file: (CODE) Sample code to add to the page menu: (CODE) Running the application, we wi…
Internet Business Fax to Email Made Easy - With  eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, f…
Many functions in Excel can make decisions. The most simple of these is the IF function: it returns a value depending on whether a condition you describe is true or false. Once you get the hang of using the IF function, you will find it easier to us…

867 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now