2

I am working on small project ASP.NET Web forms, so backend language is C#, and I want to populate checkboxlist from database, and I did it, but values I get are very strange, I need to get names of database columns or something, because right now it looks like this:

enter image description here

On windows forms I would know what to do, (DISPLAY MEMBER = "Name") and problem solved, but on the web I dont know how to get columns name, because this looks so strange..

Thanks guys,

Cheers.

7
  • Can you share the code? Commented Jul 25, 2016 at 19:39
  • 2
    You probably need to set the DataValueField and the DataTextField attributes of the CheckBoxList. Commented Jul 25, 2016 at 19:45
  • Yes @ConnorsFan, that was the answer, I was missing DataTextField, and by the way, how could I get id of selected value, I set also datavaluefield to ID from database :)) one more time thanks a lot dude :) Maybe CheckBoxList.SelectedValue ? :) Commented Jul 25, 2016 at 19:48
  • You can find some code to get the selected items in this post: stackoverflow.com/questions/18924147/…. You can then get the value for each item. (I don't think that CheckBoxList.SelectedValue is the proper way since several items can be selected.) Commented Jul 25, 2016 at 19:51
  • I used this block of code: List<ListItem> selected = checkBoxUloge.Items.Cast<ListItem>() .Where(li => li.Selected) .ToList(); and it works perfectly, could u take minute or two and explain to me/us why do the using Cast<ListItem> and why in general ListItem, thanks again dude Commented Jul 25, 2016 at 20:05

1 Answer 1

1

If the CheckBoxList is not instructed to do otherwise, it calls object.ToString() to populate the Text property of its ListItems. If ToString() is not overridden, the default implementation is this.GetType().ToString() which is what you are seeing. GetType() returns such a bizarre value because Entity Framework is dynamically subclassing your class at run-time.

My preferred way of doing this is to override ToString() to return the Name property, as it is good practice in general to override ToString() for your classes.

Another option is to assign the DataTextField property of the CheckBoxList to "Name".

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.