How to create Checkbox dynamically with windows Forms?

Asked

Viewed 138 times

0

I have a list that returns from the database and for each record I need to create a checkbox of dynamic form, I did a search and found some examples for Webforms and I need an example for Windows Forms

It would be something like this, Example:

private void CriarCheckboxDinamicamente()
        {
            try
            {
                for (int i = 0; i < 3; i++)
                {
                    this.SuspendLayout();
                    var chk = new System.Windows.Forms.CheckBox();
                    chk.Name = "Motivo" + i.ToString();
                    chk.Text = "Motivo" + i.ToString();
                    pnlModalMotivo.Controls.Add(chk);
                    this.ResumeLayout(false);
                }
            }
            catch(Exception ex)
            {
                MessageBox.Show("Erro: " + ex.Message);
            }
        }

inserir a descrição da imagem aqui

1 answer

0

The problem was that the controls were being created overlapping each other, missing to define the Location and stayed like this:

private void btnAdicionar_Click(object sender, EventArgs e)
        {
            try
            {
                int pontoX = 77;
                int pontoY = 86;
                for (int i = 0; i < 3; i++)
                {
                    this.SuspendLayout();
                    var chk = new System.Windows.Forms.CheckBox();
                    chk.Location = new Point(pontoY, pontoX);
                    chk.Name = "chk" + i.ToString();
                    chk.Text = "Motivo" + i.ToString();
                    pnlModalMotivo.Controls.Add(chk);
                    this.ResumeLayout(false);
                    pontoX = pontoX + 50;
                }
            }
            catch(Exception ex)
            {
                MessageBox.Show("Erro: " + ex.Message);
            }
        }
  • You could also use a Flowlayoutpanel for example

Browser other questions tagged

You are not signed in. Login or sign up in order to post.