C#: DataGridViewComboBoxColumn Drop Down Menu Appears All Black


I ran into an issue today using the DataGridView where one of the columns defined as a DataGridViewComboBoxColumn appeared with the drop down menu completely black as shown below.

After some research I found out that there is a documented bug in the DataGridViewComboBoxColumn where this sometimes occurs if you are handling the EditingControlShowing event of the DataGridView. I am handling this event in order to wire up the SelectedIndexChanged event of the ComboBox embedded in the DataGridView cell.

On the bug report, Microsoft states that they will not be fixing this bug but thankfully, Debanjan1 has posted a workaround for this issue. If you simply set the CellStyle.BackColor property to the DataGridView.DefaultCellStyle.BackColor in the EditingControlShowing event, the problem goes away. This is shown below.

private void dataGridViewGLEntries_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
    ComboBox cmbBx = e.Control as ComboBox;

    if (cmbBx != null)
    {
        cmbBx.SelectedIndexChanged -= ComboBoxCell_SelectedIndexChanged;
        cmbBx.SelectedIndexChanged += ComboBoxCell_SelectedIndexChanged;

        // Fix the black background on the drop down menu
        e.CellStyle.BackColor = this.dataGridViewGLEntries.DefaultCellStyle.BackColor;
    }
}

C#: Calling a Constructor from Another Constructor in the Same Class


If you have a child class that extends or inherits from another class, you can ensure a specific constructor in the parent class is called by using the : base() syntax as shown below.

public class Parent
{
    public Parent()
    {
        // Empty constructor called by default        
    }

    public Parent(int value)
    {
        this.Value = value;       
    }
}

public class Child : Parent
{
    public Child(int value) : base(value)
    {
        // Using the base keyword and supplying the value
        // parameter, ensures that the second constructor
        // in the Parent class is called rather than
        // the first
    }
}

In the example above, when creating a new Child object, the second constructor in the Parent class will be called instead of the first. But, what if you want to call one constructor from another in the same class? Take the example below, where each constructor assigns a value to the DistanceTraveled variable.

public class Trip
{    
    public Trip(decimal distanceTraveled)
    {
        this.DistanceTraveled = distanceTraveled;   
    }

    public Trip(decimal travelTime, decimal velocity)
    {
        this.DistanceTraveled = travelTime * velocity;
    }
}

While this code works, you are updating the DistanceTraveled variable in two different places which is less than desirable from a maintenance perspective (understandably this is a trivial example but with little thought I’m sure you can think of a real world situation where this would this could cause a larger problem). It would be nice to be able to call the first constructor from the second, passing in the product of the two parameters. Using the base keyword won’t work in this situation as we want to call a constructor in the same class, not a parent class. It turns out that if we simply swap ‘base’ for ‘this’, our goal can be achieved.

public class Trip
{    
    public Trip(decimal distanceTraveled)
    {
        this.DistanceTraveled = distanceTraveled;
    }

    public Trip(decimal travelTime, decimal velocity) : this (travelTime * velocity)
    {
        // the DistanceTraveled variable is updated by a call to the first constructor
    }
}

C#: FTP Upload Error – The remote server returned an error: (550) File unavailable (e.g., file not found, no access).


I developed an application a while back that automatically backs up a group of SQL servers every night and then uploads the backups to an offsite location using FTP. The application has worked flawlessly for months now so I was quite surprised to get a call this morning saying that the automatic backups failed last night. I checked the error logs and saw a 550 error – “The remote server returned an error: (550) File unavailable (e.g., file not found, no access).” I then ran the program through a debugger again saw that this exception was thrown while attempting to close the FileStream.

I tested for the usuals, spaces in the ftp uri, ensuring correct permissions for ftp user, changed the code around to see if it was a coding issue, and a bunch of other things and nothing seemed to fix the problem. I could login to the server with the same credentials using Windows Explorer and FileZilla and I could upload a test text file. I had no idea what was going on. So, after a long time, too long, I whipped out good ol’ WireShark to see if I could discern anything from the actual packet transfer (something I should have done first!) and lo and behold, there I found the error in plain text.

“There is not enough space on the disk.” Such a problem did not cross my mind as the hosting plan we pay for comes with unlimited disk space! Further, the test file I uploaded was a couple of KB rather than the 4 or 5 MB backups that were trying to be uploaded so I wasn’t seeing the error. Turns out despite what it says in the contract, there are still physical limits on the server. Ridiculous! :) After a short call to the hosting company the problem was resolved.

Despite the fact that the server was giving the real reason for the error, the .NET Framework did not relay the message. Kind of strange if you ask me but such is life. Nonetheless, a valuable lesson was learned: when debugging FTP issues, always pull out WireShark!

Posted in .NET Framework. Tags: , , . 4 Comments »

C#: String Concatenation using StringBuilder and LINQ Aggregate Function


I always forget how to do this so I thought I would post it mainly for my reference.

List<string> nameList = new List<string>() { "Roger", "Clark", "Wonda", "Anita" };

// A useless Select call in this instance just to remind you
// that you coulde use LINQ to select a set of strings
// from a list of objects
StringBuilder names = nameList.Select(n => n)
                              .Aggregate(new StringBuilder(), (current, next) => current.Append(next).Append(", "));

// Remove the trailing comma and space
if (names.Length > 1)
    names.Remove(names.Length - 2, 2);

Console.WriteLine(names.ToString());

// Output
// ------
// Roger, Clark, Wonda, Anita

C#: Yield Statement Used to Reduce Accessor Code


Often in Windows Forms development I run into the situation where I need to show a list of items to a user from which they can select multiple items. Usually I will accomplish this using a dialog form with a CheckedListBox. The user simply checks the box next to each item they want to select and then clicks OK. For example, here is one that allows a user to override various form letter merge fields.

Before today, I would include an accessor method in the form class similar to the following:

public List<string> SelectedFields
{
    get
    {
        List<string> selectedFields = new List<string>();

        foreach (var item in this.listBxMergeFields.CheckedItems)
            selectedFields.Add(item.ToString());

        return selectedFields;
    }
}

I always thought it was a pain to have to instantiate a new List object and populate it when I wasn’t performing any operations on the List other than adding items. Enter the yield statement. It turns out that the following code can be used to solve my little annoyance.

public IEnumerable<string> SelectedFields
{
    get
    {
        foreach (var item in this.listBxMergeFields.CheckedItems)
            yield return item.ToString();
    }
}

When used in this fasion, the yield statement will return the accumulated values that result from the expression to its right. Pretty handy way to tidy up the code if you ask me! For more information and uses, check the MSDN documentation here.

(I admit this is a relatively trivial way of using this as we are just enumerating over one collection to create another, but the concept can be applied to other situations.)

C#: Method with Arbitrary or Variable Number of Parameters


Normally when I create a method that needs to accept an arbitrary or variable number of parameters or arguments I just accept an array of values. This works great but it does require you to instantiate a new array and populate it every time you want to call the method. Not a big deal but as you can see below it makes the code a bit messy.

static void Main(string[] args)
{
    CountParameters(new int[] { });
    CountParameters(new int[] { 5, 3, 6 });
    CountParameters(new int[] { 1, 2, 3, 4 });
    CountParameters(new int[] { 8, 3, 78, 234, 2, 56, 87 });
}

public static void CountParameters(int[] numbers)
{
    Console.WriteLine(numbers.Length + " parameters passed in");
}

// Output
// ------
// 0 parameters passed in
// 3 parameters passed in
// 4 parameters passed in
// 7 parameters passed in

But, if you simply add the ‘params’ keyword before the parameter definition, this allows you to call the method by just specifying a comma delimited list of arguments.

static void Main(string[] args)
{
    CountParameters();
    CountParameters(5, 3, 6);
    CountParameters(1, 2, 3, 4);
    CountParameters(8, 3, 78, 234, 2, 56, 87);
}

public static void CountParameters(params int[] numbers)
{
    Console.WriteLine(numbers.Length + " parameters passed in");
}

// Output
// ------
// 0 parameters passed in
// 3 parameters passed in
// 4 parameters passed in
// 7 parameters passed in

You can also specify other parameters for the method but the parameter with the ‘params’ keyword must be the last parameter definition. Further you can only add the ‘params’ keyword to one parameter in the list of parameters. More information about the ‘params’ keyword can be found here.

Interestingly, if you look at the disassembly of the second code segment above, you will see the following:

private static void Main(string[] args)
{
    CountParameters(new int[0]);
    CountParameters(new int[] { 5, 3, 6 });
    CountParameters(new int[] { 1, 2, 3, 4 });
    CountParameters(new int[] { 8, 3, 0x4e, 0xea, 2, 0x38, 0x57 });
    Console.ReadLine();
}

public static void CountParameters(params int[] numbers)
{
    Console.WriteLine(numbers.Length + " parameters passed in");
}

It simply instantiates a new array of integers and passes it to the CountParameters method as we did in the first approach. So this is obviously just a way to make your code a bit more readable.

LINQ: Selecting Multiple Properties from a List of Objects


In a previous post I discussed how to use LINQ to flatten a list of lists. Yesterday and ran across a slightly different situation but that used the same solution.

I had a list of objects that each contained three separate integer values and I wanted to extract the three values from each object and put them all in a single list. So, all you need to do is create a new List that has each of the three values in each object as elements of the list and then use the SelectMany method to flatten the list of lists we just created.

private class Foo
{
    public int Item1;
    public int Item2;
    public int Item3;
}

static void Main(string[] args)
{
    List<Foo> foos = new List<Foo> 
                           { 
                               new Foo() { Item1 = 1, Item2 = 2, Item3 = 3 },
                               new Foo() { Item1 = 4, Item2 = 5, Item3 = 6 },
                               new Foo() { Item1 = 7, Item2 = 8, Item3 = 9 }
                           };

    // Create a list of lists where each list has three elements corresponding to 
    // the values stored in Item1, Item2, and Item3.  Then use SelectMany
    // to flatten the list of lists.
    var items = foos.Select(f => new List<int>() { f.Item1, f.Item2, f.Item3 }).SelectMany(item => item).Distinct();

    foreach (int item in items)
        Console.WriteLine(item.ToString());
    
    Console.ReadLine();
}

// Output
// ------
// 1
// 2
// 3
// 4
// 5
// 6
// 7
// 8
// 9
Posted in LINQ. Tags: , . 2 Comments »
Follow

Get every new post delivered to your Inbox.

Join 70 other followers