1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

ASP.NET 2.0 problem dynamically populating a checkboxlist control

Discussion in 'C#' started by itcn, Jun 10, 2008.

  1. #1
    I'm having a problem dynamically populating a checkboxlist control. The checkboxlist control is simple:

    <asp:CheckBoxList id="thisCompanyList" runat="server" />

    And here's the VB code to populate it from a database loop:

    thisCompanyList.Items.Add(new ListItem(myReader("CompanyName").ToString(), myReader("CompanyID").ToString()))

    I was under the impression this is the method to populate a checkbox (or radio) list - did this change in .NET 2.0 that I'm not aware of?

    control.Items.Add(new ListItem("Text", "Value"))

    The problem I am having is my code populates both the text and value with whatever text I put first, so I know it's not a SQL select problem. If I list the company Name first, both the value and text are the company Name. If I list the company ID, then both the value and text for the checkboxes are the ID. So I am properly pulling the values from the database. The problem is with the syntax I am using to populate the text and value fields for the checkbox. Any help is appreciated, tia~!
     
    itcn, Jun 10, 2008 IP
  2. yugolancer

    yugolancer Well-Known Member

    Messages:
    320
    Likes Received:
    8
    Best Answers:
    0
    Trophy Points:
    110
    #2
    You should bind the checkbox list to a datareader like following

    ' assuming that GetListItems returns a list of comanyname and companyid items in a satareader object
    Dim myReader As SqlDataReader = GetListItem()
    thisCompanyList.DataSource = myReader
    thisCompanyList.DataValueField = "CompanyID"
    thisCompanyList.DataTextField = "CompanyName"
    thisCompanyList.DataBind()
    Code (markup):
    HTH
    Regards :)
     
    yugolancer, Jun 10, 2008 IP
    itcn likes this.
  3. itcn

    itcn Well-Known Member

    Messages:
    795
    Likes Received:
    31
    Best Answers:
    0
    Trophy Points:
    118
    #3
    yugolancer; thanks for that, that's another way to do it and it works perfectly.

    I did solve my particular problem -- it was (of course) just a bug in my code elsewhere. On parsing the submitted results of the checkboxlist I was pulling thisCompanyList.Items(i).Text instead of thisCompanyList.Items(i).Value.

    Thanks again!
     
    itcn, Jun 10, 2008 IP
  4. yugolancer

    yugolancer Well-Known Member

    Messages:
    320
    Likes Received:
    8
    Best Answers:
    0
    Trophy Points:
    110
    #4
    Alright, good you solved it.
     
    yugolancer, Jun 11, 2008 IP