简体   繁体   中英

What's the C# equivalent of the following VB.NET code?

I have this code written in VB.NET that I need to convert to C# but I'm running in some problems.

This is the code in VB:

For Each c in Me.Controls
    If TypeOf (c) Is PictureBox Then
        CType(c,PictureBox).Image = icon;
        AddHandler c.Click, AddressOf PictureBox10_Click
    End If

So basically I'm trying to make it check for PictureBoxes and give them an icon and to make those PictureBoxes have the same function that PictureBox10 Click event has.

Here is the code I've written in C#:

foreach (Control c in this.Controls)
{
    if (c.GetType() == typeof(System.Windows.Forms.PictureBox))
    {
        ((PictureBox)c).Image = Properties.Resorces.available;
        c.Click += new System.EventHandler(this.pictureBox10_Click);
    }
}

It works till the Image part but I can't get the EventHandler working.

Also here is what the PictureBox10 Click Event does:

private void pictureBox10_Click(object sender, EventArgs e) 
{
    if (pictureBox10.Image == Properties.Resorces.available)
        pictureBox10.Image = Properties.Resorces.selected;
    else if (pictureBox10.Image == Properties.Resorces.selected)
        pictureBox10.Image = Properties.Resorces.available;
}

Any help is very much appreciated.

The code to select a picturebox can be simplified using the System.Linq extension method, OfType , which selects only the controls specified in the OfType argument, and returns them as that type. Also, we can assign a common event hanlder to all these controls:

foreach (PictureBox pb in Controls.OfType<PictureBox>())
{
    pb.Image = Properties.Resorces.available;
    pb.Click += PictureBox_Click;  // Defined below
}

Then in the event handler, we cast sender to a PictureBox so that we have a strongly-typed object, which allows us to then set the Image property:

private void PictureBox_Click(object sender, EventArgs e)
{
    var thisPictureBox = sender as PictureBox;

    // May not be necessary, but it's a good practice to ensure that 'sender' was actually
    // a PictureBox and not some other object by checking if 'thisPictureBox' is 'null'
    if (thisPictureBox == null) return;

    if (thisPictureBox.Image == Properties.Resorces.available)
    {
        thisPictureBox.Image = Properties.Resorces.selected;
    {
    else if (thisPictureBox.Image == Properties.Resorces.selected)
    {
        thisPictureBox.Image = Properties.Resorces.available;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM