Solved

Can't automatically select a databound checkboxListItem

Posted on 2006-07-20
8
415 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
Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

 

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

Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

Join & Write a Comment

Lots of people ask this question on how to extend the “MembershipProvider” to make use of custom authentication like using existing database or make use of some other way of authentication. Many blogs show you how to extend the membership provider c…
I have developed many web applications with asp & asp.net and to add and use a dropdownlist was always a very simple task, but with the new asp.net, setting the value is a bit tricky and its not similar to the old traditional method. So in this a…
This tutorial demonstrates a quick way of adding group price to multiple Magento products.
You have products, that come in variants and want to set different prices for them? Watch this micro tutorial that describes how to configure prices for Magento super attributes. Assigning simple products to configurable: We assigned simple products…

706 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

18 Experts available now in Live!

Get 1:1 Help Now