How to bind Enum from DataTable to win forms CheckedListBox
i have this scenario:
[Flags] enum Colors : long ( red = 1, blue = 2, green = 4, yellow = 8, ) DataTable dt = new DataTable(); dt.Columns.Add("PersonName", typeof(string)); dt.Columns.Add("CheckOption", typeof(bool)); dt.Columns.Add("Colors", typeof(long)); // note that the values in the Colors column are enumed values of chosen colors dt.Rows.Add("Name 1", true, 1); // red dt.Rows.Add("Name 2", true, 12); // green and yellow dt.Rows.Add("Name 3", true, 4); // green dt.Rows.Add("Name 4", false, 11); // red, blue and yellow // bind the datatable to grid DataGridView dgv = new DataGridView(); dgv.DataSource = dt; // hide the colors in the grid dgv.Columns["Colors"].Visible = false; // checked list box has all items from the enum CheckedListBox clb = new CheckedListBox(); string colorsArray = Enum.GetNames(typeof(Colors)); clb.Items.AddRange(colorsArray);
what i'd like is to somehow bind the enumed value of chosen colors in datatable's "Colors" column to the CheckedListBox in a nice way. is it possible?
so far i've been playing with grid's RowEnter event but this seems very brittle and not really nice at all.
EDIT: for example if i had a 4th column in the datatable called MyText i could bind that column to a text box like this:
myTextBox.DataBindings.Add("Text", dt, "MyText");
when moving through the rows in a datagrid the value in the textbox automaticaly changes and any updates to the textbox are saved back to the datatable. i would like to get this functionalty from the checklistbox and enums too.
I'm not exactly sure what you're after, but can you use a greedy algorithm to determine which colours are being used?
For instance, you have the number 11. The only possible way to get 11 is by having yellow, so you remove the biggest number that fits (8), and check the corresponding checkbox. Then you get 3. Biggest number that fits is 2 (blue), then the remainder is obvious.