Initially I had the following:
[Flags]
public enum QueryFlag
{
None = 0x00,
CustomerID = 0x01,
SalesPerson = 0x02,
OrderDate = 0x04
}
As check boxes are checked/unchecked, I would add/remove flags from:
QueryFlag qflag;
My idea – when the user clicks the Search button, I would iterate the actual flags set in qflag to modify a .Where clause in my LINQ to Sql. However, Enum.GetValues(qflag.GetType()) returns all the values of the QueryFlag itself. Not helpful.
My solution:
class myForm : Form
{
List<QueryFlag> qflag = new List<QueryFlag>();
private void chkOrderDate_CheckedChanged(object sender, EventArgs e)
{
if (chkOrderDate.Checked && !qflags.Contains(QueryFlag.OrderDate))
qflags.Add(QueryFlag.OrderDate);
else
qflags.Remove(QueryFlag.OrderDate);
}
private void cmdSearch_Click(object sender, EventArgs e)
{
if (qflags.Count == 0)
{
rtfLog.AppendText("\nNo search criteria selected.");
return;
}
foreach (QueryFlag flag in qflag)
{
rtfLog.AppendText(string.Format("\nSearching {0}", flag.ToString()));
// add switch for flag value
}
}
}
public enum QueryFlag
{
CustomerID,
SalesPerson,
OrderDate
}
I have 3 check boxes and this works without any issues to this point. But I am wondering if there is a better way to perform this iteration.
The way you had it originally was correct; you just got messed up by the
Enum.GetValuesmethod. This method returns every defined value for a particularenumtype, yes. So what you do with this is check each defined value against your particularenumvalue to see whether the defined value is set within your value.That is, you should do this:
…and likewise for your other CheckBoxes. Then when you want to enumerate what flags you have set:
In fact, you could even abstract the above into a handy extension method for all
enumtypes:So your
cmdSearch_Clickhandler could look like this: