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.

  • Can you share the code? – Humayun Shabbir Jul 25 '16 at 19:39
  • 2
    You probably need to set the `DataValueField` and the `DataTextField` attributes of the CheckBoxList. – ConnorsFan Jul 25 '16 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 ? :) –  Jul 25 '16 at 19:48
  • You can find some code to get the selected items in this post: http://stackoverflow.com/questions/18924147/how-to-get-values-of-selected-items-in-checkboxlist-with-foreach-in-asp-net-c. 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.) – ConnorsFan Jul 25 '16 at 19:51
  • I used this block of code: `List selected = checkBoxUloge.Items.Cast() .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 and why in general ListItem, thanks again dude –  Jul 25 '16 at 20:05
  • Overriding `ToString()` in your class would also do the trick. – Mr Anderson Jul 25 '16 at 20:27
  • I am not a LINQ expert but I think that the `Cast` is used to transform an `IEnumerable` into an `IEnumerable`, so that it can be queried with LINQ methods (see this article: http://weblogs.asp.net/fmarguerie/querying-non-generic-collections-with-linq-to-objects). – ConnorsFan Jul 25 '16 at 20:35

1 Answers1

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".

Mr Anderson
  • 2,200
  • 13
  • 23