tags:

views:

1460

answers:

2

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.

A: 

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.

Jean Azzopardi
i don't have a problem with finding out which colors are chosen. what i want is to bind those values to the checked list box so i wouldn't have to do this calculation each time a row in datagrid is selected.
Mladen Prajdic
I'm sorry, I wouldn't know how to do that. However, I believe even if you're going to bind those values, you're still going to recalculate each time the row is selected, right? It's just more abstracted.
Jean Azzopardi
yeah i guess i'll have to... i was looking for an easy way out :)
Mladen Prajdic
+1  A: 

There is no easy way to do it as this is not a typical master detail scenario. I guess you should start writting that code afterall.

Miha Markic