sara
sara

Reputation: 63

How to make Combo Box using WinForms and C#

I am new to WinForms coding and I am trying to make this minipaint which has 3 buttons (circle, line and rectangle). Here are my buttons:

private void circle_btn_Click(object sender, EventArgs e)
{
    circle c = new circle() {startx=10,thickness=4,starty=10,radius=100,color=Color.Black };
    shapes.Add(c);
    panel1.Invalidate();
}
private void rectangle_btn_Click(object sender, EventArgs e)
{
    rectangle r = new rectangle() { startx = 10,thickness=4, starty = 10, length = 200, width = 100, color = Color.Black };
    shapes.Add(r);
    panel1.Invalidate();
}

private void line_btn_Click(object sender, EventArgs e)
{
    line l = new line() {startx=10,starty=10,thickness=4,endx=200,endy=200,color=Color.Black };
    shapes.Add(l);
    panel1.Invalidate();
}

When I click on them, a random shape will be printed on my Panel. I want to make a ComboBox , which has these three values(circle, line and rectangle) which lets me choose one of them in order to change it's properties in a PropertyGrid. I tried something like:

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    Button namestr = line_btn;
    comboBox1.Items.Add(namestr);
}

but I know it is not right. How am I suppose to do that?

Upvotes: 0

Views: 271

Answers (1)

Mong Zhu
Mong Zhu

Reputation: 23732

what you could do is to populate your ComboBox first eg. in the constructor:

public Form1()
{
   comboBox1.Items.AddRange(new List<string>() { "circle", "line", "rectangle"}.ToArray());
}

or you take already an array:

public Form1()
{
   comboBox1.Items.AddRange(new string []{ "circle", "line", "rectangle"});
}

and switch according to the values in the SelectedIndexChanged event:

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    switch (comboBox1.SelectedItem.ToString())
    {
        case "circle":
            //do something circular
            break;
        case "line":
            //do something linish
            break;
        case "rectangle":
            //do something edgy
            break;
        default:
            break;
    }
}

Upvotes: 1

Related Questions