Home > Software design >  Dynamically Create Buttons based off of SQL Column
Dynamically Create Buttons based off of SQL Column

Time:11-26

I am trying to write a piece of code that would pull from my SQL column and create one button per value in that column. For example, if I have column A with "test 1", "test 2", and "test 3", the code should produce three buttons which also hold the text from that value.

enter image description here

Here is what I have tried so far. This code only gives me one button and it is blank.

 private void button7_Click(object sender, EventArgs e)
        {

            SqlConnection conn = new SqlConnection(@"connstring");
            string strsql;
            strsql = "SELECT buttonID from table1 ";
            SqlCommand cmd = new SqlCommand(strsql, conn);
            SqlDataReader reader = null;
            cmd.Connection.Open();
            reader = cmd.ExecuteReader();
            while (reader.Read())
            {           
                Button newButton = new Button();
                newButton.Text = reader["buttonID"].ToString();
                newButton.Location = new Point(1, 10);
                newButton.Size = new Size(100, 50);
                this.Controls.Add(newButton);
            }

        }

UPDATE As mentioned in the comments, I had no way of naming my buttons, so I have added that function in. And as to why I was only seeing one button, I am assuming it is because all of the buttons are being created on top of each other, rather than displaying in rows or in columns.

CodePudding user response:

You need to work on few things here.

First, check the records in the table, Do you really have 3 records? because As per your code it should work for 3 buttons.

Second, you are not setting the text of the button.

Use using with the SqlConnection and SqlCommand objects while initialling it.

And please define your connection string in some config file.

CodePudding user response:

To counter the issue I was facing, which ended up being buttons having no text and all displaying on top of each other, I added a FlowLayoutPanel and added the buttons(controls) into. Thanks for the previous answers that helped me solve this.

 private void button7_Click(object sender, EventArgs e)
        {

            SqlConnection conn = new SqlConnection(@"connstring");
            string strsql;
            strsql = "SELECT buttonID from table1 ";
            SqlCommand cmd = new SqlCommand(strsql, conn);
            SqlDataReader reader = null;
            cmd.Connection.Open();
            reader = cmd.ExecuteReader();
            while (reader.Read())
            {           
                Button newButton = new Button();
                newButton.Text = reader["buttonID"].ToString();
                newButton.Size = new Size(100, 50);
                this.Controls.Add(newButton);
                flowLayoutPanel1.Controls.Add(newButton);
            }

        }
  • Related