How to ensure that a cell is visible in a DataGridView control
17 May 07 10:51 AM | aalexandrov | 1 Comments   
To ensure that a cell is visible just simply set the CurrentCell property of the DataGridView control. The DataGridView control automatic scroll if it is not visible.
How to set ColumnWidth of a range in pixels in Excel’s worksheet with C#
02 May 07 07:39 AM | aalexandrov | 0 Comments   

Opa … today I have searched for a function that converts my pixel’s width of a column in a DataGridView control to a ColumnWidth of an excel’s range object …. but unfortunately I have not found such and I have to write myself such. Here it is the code:

  // Get the column width
  private float GetColumnWidth(Worksheet ws, int colIndex)
  {
      return float.Parse(((Range)ws.Cells[1, colIndex]).EntireColumn.ColumnWidth.ToString());
  }
 

  // Get the column width in pixels
  private float GetColumnWidthInPixels(Worksheet ws, int colIndex)
  {
      return float.Parse(((Range)ws.Cells[1, colIndex]).EntireColumn.Width.ToString());
  }
  

  // Calculate the column width characters to point ratio
  private float GetColumnWidthCharactersForPointRatio(Worksheet ws)
  {
      float colWidth = GetColumnWidth(ws, 1);
      float widthInPixels = GetColumnWidthInPixels(ws, 1);
     

      return widthInPixels / colWidth;
  }

The last function is the key for all excel column width specific operations - it gives the ratio between the normal ColumnWidth (in characters) and the pixel’s width. From now on you just have to set your own width in the following way:
((Range)ws.Cells[1, colIndex]).EntireColumn.ColumnWidth = YOUR_OWN_CUSTOM_WIDTH_IN_PIXELS / RATIO;

If you have any suggestions for easier way go on and post it :)

Filed under:
DefaultCellStyle.BackColor = Color.Empty problem in the DataGridView control
02 May 07 07:38 AM | aalexandrov | 0 Comments   
Today I had a very strange problem in my DataGridView control. I have set for DefaultCellStyle.BackColor property of the DataGridView control a value Color.Empty , after that I have tried to set different colors, but no one of them is applied …. could anyone tell me why?
Filed under:
Using the keyword ‘yield’ in C#
02 May 07 07:37 AM | aalexandrov | 0 Comments   

Hi folks, today I’ve discovered that the basic C# language specification is escaping me. I keep discovering new features of the language itself. I have found the keyword ‘yield’ in C#. It takes one of the forms: ‘yield return expression‘ or ‘yield break’. Now lets explain the use of the keyword in a brief example:

public class DaysOfTheWeek : IEnumerable
{
        string[] m_Days = { “Sun”, “Mon”, “Tue”, “Wed”, “Thr”, “Fri”, “Sat” };

        public IEnumerator GetEnumerator()
        {
                yield return m_Days[0];
                yield return m_Days[2];

                yield return m_Days[4];
                yield break;

        }
}

class TestDaysOfTheWeek
{
        static void Main()

        {
              // Create an instance of the collection class
                DaysOfTheWeek week = new DaysOfTheWeek();

                // Iterate with foreach
                foreach (string day in week)

                {
                        System.
Console.Write(day + ” “);
                }
                // Iterate with the IEnumerator
                IEnumeratormyEnumerator = week.GetEnumerator();
                while(myEnumerator.MoveNext() == true)
                {
                        System.
Console.Write(myEnumerator.Current + ” “);
                }
        }

}
Now … when we have a class that has a collection of items and if we want to provide an access to that collection. There are many ways providing that but the simplest is to make an iterator.  An iterator is a method, get accessor or an operator that enables us to support foreach statements in an enumeration or a class. Let’s explain what is happened behind the scene. First the compiler ‘detect’ that our class DaysOfWeek implements the interface IEnumerable so it has a function called GetEnumerator() which returns an object of type implementing the interface IEnumerator or it is an iterator. If in the function there is a ‘yield’ keyword the compiler decides that this function is an iterator and generates automatically a class that implements the IEnumerable interface and generates its Current, MoveNext and Dispose methods.  Now on each successive iteration of the foreach loop (or the direct call to myEnumerator.MoveNext), the next iterator code body resumes after the previous yield statement and continues to the next until the end of the iterator body is reached, or a yield break statement is encountered. So the picture is something like that:

1. IEnumerator myEnumerator = week.GetEnumerator(); - gets an instance of the class generated by the compiler witch provides iteration.

2. myEnumerator.MoveNext() - Finds the first ‘yield return’ statement. If the compiler finds ‘yield break’ or gets out of scope MoveNext() returns false and the while breaks

3. myEnumerator.Current - gets the expression returned by the ‘yield return’ statement.

4. myEnumerator.MoveNext() - Finds the next ‘yield return’ statement bellow the first one. If the compiler finds ‘yield break’ or gets out of scope MoveNext() returns false and the while breaks

…..
The result of the execution of the program is the output: “Sun Tue Thr”.  This is how you can do a specific ways to iterate through your composed data structure. You could provide one iterator which returns elements in ascending order, and one which returns elements in descending order or even in reversed order. An iterator that takes the elements in reversed order is just like this:

public IEnumerator GetEnumerator()
{
    for (int ndx = m_Days.Length - 1; ndx >= 0; ndx—)

    {
        yield return m_Days[ndx];
    }
}

So it is quite pretty to implement an iterator and to use it, don’t you think? :)

Filed under:
.NET memory managment or just another advertising trick :)
02 May 07 07:35 AM | aalexandrov | 0 Comments   

Hi folks,

today is a very bad day, cause it is Monday :) But for Micro$oft this is a day of CLR bugs (CLR = Common Language Runtime). Now let’s illustrate a sample program and the problem it causes. I have wrote a program to see what is the Memory Management in .NET and how does it handles with Out Of Memory problems … and guess what - it does not handles so well :) Here is the code:

private void button1_Click(object sender, EventArgs e)
{
   List<byte[]> bytes = new List<byte[]>();
   while (true)
   {
      byte[] barray = new byte[10000];

      bytes.Add(barray);
   }
}

It is very obvious that I wanted to see when the OutOfMemoryException is thrown, but unfortunately I get this:

FatalExecutionEngineError was detectedMessage: The runtime has encountered a fatal error. The address of the error was at 0×79fce5c2, on thread 0×928. The error code is 0xc0000005. This error may be a bug in the CLR or in the unsafe or non-verifiable portions of user code. Common sources of this bug include user marshaling errors for COM-interop or PInvoke, which may corrupt the stack. 

Can anyone answer what the f.ck is this? Maybe this is really a bug in their good generic List class? What do you think ;)?

Filed under:
Styles inheritance in DataGridView control
02 May 07 07:30 AM | aalexandrov | 0 Comments   

The new DataGridView control for tabular data manipulation provides a large capabilities for its appearance management. The basic class for all visual styles in the DataGridView is the DataGridViewCellStyle. This class implements some properties for changing the font, the background color of the cell, the color of the font, alignments, padding, wrapping modes and so on. Now lets explain the priorities of all cell styles and the styles itself:

1. DataGridView.DefaultCellStyle - This is the default cell style of all cells in the DataGridView control (including row and column header cells). If no other style is defined this style is applied to all cells.

On the second level the DataGridView control is divided on three logical parts. Column Header Cells, Row Header Cells and the sub-table excluding this cells. Lets see the styles for each logical part:

1.1 DataGridView.ColumnHeadersDefaultCellStyle - This is the default cell style for all column header cells including the top left header cells (the top left corner cell of the table). If this style is not defined a DataGridView.DefaultCellStyle is applied for all column header cells.

1.2 DataGridView.RowHeadersDefaultCellStyle - This is the default cell style for all row header cells . If this style is not defined a DataGridView.DefaultCellStyle is applied for all row header cells.

For Column Header and Row Header Cells if the enable header visual styles property of the DataGridView control is set the DataGridView.ColumnHeadersDefaultCellStyle and the DataGridView.RowHeadersDefaultCellStyle are overridden by the current theme.

1.3 DataGridViewColumn.DefaultCellStyle - This is the style used by all cells in the sub-table’s column. For every column in the Columns collection of the DataGridView such style can be defined. If it is not defined a DataGridView.DefaultCellStyle is applied for all cells of the sub-table’s column.

1.3.1 DataGridView.RowsDefaultCellStyle - This is the style used by all cells in the sub-table. If this style is not defined for every column of the sub-table is used its DataGridViewColumn.DefaultCellStyle.

1.3.1.1 DataGridView.AlternatingRowsDefaultCellStyle - This style is used by all cells in the alternating rows in the sub-table, creating a ledger like effect. If this style is not defined a DataGridView.RowsDefaultCellStyle is applied for all alternating row’s cells.

1.3.1.1.1 DataGridViewRow.DefaultCellStyle - This style is used by all cells in a single row of the subtable. Now one row in the subtable can be alternating or regular. If this property is not defined for the single row there are two cases:

- A DataGridView.AlternatingRowsDefaultCellStyle is applied if the row is alternating;

- A DataGridView.RowsDefaultCellStyle is applied if the row is regular;

Every cell of the DataGridView control has its own DataGridViewCell.Style property. If it is set it override every other style on the higher level mentioned above. If it is not set the exact style is DataGridViewCell.InheritedStyle which is examined from all higher level styles.

So if you want to change the style of some cells in the DataGridView control it is very important to understand the styles inheritance and see that you can manage styles on a single cell level or higher (global) level.

Filed under:

Search

Go

This Blog

Archives

Syndication