Question

I'm having some problems with the following:

  • I want to get the first visible AND frozen column of a column collection.

I think this will do it:

DataGridViewColumnCollection dgv = myDataGridView.Columns;
dgv.GetFirstColumn(
     DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen);
  • Is it also possible to make a bitmask to get the first frozen OR visible column?
Was it helpful?

Solution

The implementation is, AFAIK, "all of these" - it uses:

((this.State & elementState) == elementState);

Which is "all of". If you wanted to write an "any of", perhaps add a helper method: (add the "this" before DataGridViewColumnCollection to make it a C# 3.0 extension method in)

    public static DataGridViewColumn GetFirstColumnWithAny(
        DataGridViewColumnCollection columns, // optional "this"
        DataGridViewElementStates states)
    {
        foreach (DataGridViewColumn column in columns)
        {
            if ((column.State & states) != 0) return column;
        }
        return null;
    }

Or with LINQ:

        return columns.Cast<DataGridViewColumn>()
            .FirstOrDefault(col => (col.State & states) != 0);

OTHER TIPS

Well, bitmasks usually work like this:

| is joining flags up. & is filtering subset of flags from a flag set represented by a bitmask. ^ is flipping flags by a mask (at least in C/C++).

To get the first frozen OR visible column GetFirstColumn must handle bitmasks different way (e.g. GetFirstColumn could get the first column that matches any of the flags set, but this is not the case).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top