concatenate Rectangle control name for shape in c#

255 Views Asked by At

This is in WinForms. and i am using microsoft.vsualbasic.powerpacks how can i concatenate Rectangle control name in c# this is what i have so far

  string n = "1";
  Rectangle match = this.Controls.Find("rectangleShape" + n,true)[0] as Rectangle;
  match.BackColor = Color.Red;
1

There are 1 best solutions below

0
On

Try some of the solutions here... – Idle_Mind

okay will do try – droid fiji

it didnt really help :( – droid fiji

Here's a working example based on the solution I linked to in the comments. Note that the BackStyle property of your RectangleShape needs to be Opaque for you to see the color you set!

This code will set the BackColor of rectangeShape1 thru rectangeShape3 to Red:

using Microsoft.VisualBasic.PowerPacks;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string rectName;
            string rectBaseName = "rectangleShape";
            var shapeContainer = this.Controls.OfType<ShapeContainer>().FirstOrDefault();
            if (shapeContainer != null)
            {
                for (int i = 1; i <= 3; i++)
                {
                    rectName = rectBaseName + i.ToString();
                    RectangleShape match = shapeContainer.Shapes.OfType<RectangleShape>().FirstOrDefault(o => o.Name == rectName);
                    if (match != null)
                    {
                        match.BackColor = Color.Red;
                        match.BackStyle = BackStyle.Opaque;
                    }
                }
            }      
        }

    }

}