Solved

Can't automatically select a databound checkboxListItem

Posted on 2006-07-20
8
418 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
Microsoft Certification Exam 74-409

Veeam® is happy to provide the Microsoft community with a study guide prepared by MVP and MCT, Orin Thomas. This guide will take you through each of the exam objectives, helping you to prepare for and pass the examination.

 

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
 

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

Netscaler Common Configuration How To guides

If you use NetScaler you will want to see these guides. The NetScaler How To Guides show administrators how to get NetScaler up and configured by providing instructions for common scenarios and some not so common ones.

Question has a verified solution.

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

Today is the age of broadband.  More and more people are going this route determined to experience the web and it’s multitude of services as quickly and painlessly as possible. Coupled with the move to broadband, people are experiencing the web via …
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…
This Micro Tutorial will give you a basic overview how to record your screen with Microsoft Expression Encoder. This program is still free and open for the public to download. This will be demonstrated using Microsoft Expression Encoder 4.
Although Jacob Bernoulli (1654-1705) has been credited as the creator of "Binomial Distribution Table", Gottfried Leibniz (1646-1716) did his dissertation on the subject in 1666; Leibniz you may recall is the co-inventor of "Calculus" and beat Isaac…

777 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