DmO DmO - 7 months ago 17
SQL Question

Create Dynamic Button from Sql

I saved my button properties into my database. When i open my form i want to create a button with this properties.
I'm trying something like that. But i dont have results.
Should i use something else instead of that?

SqlCommand command = new SqlCommand("select * from button_properties", con);
con.Open();
SqlDataReader read = command.ExecuteReader();
Button dynamicButton = new Button();

dynamicButton.Height = (read["height"].ToString());
dynamicButton.Width = (read["width"].ToString());
dynamicButton.Text = (read["text"].ToString());
dynamicButton.Name = (read["name"].ToString());
dynamicButton.Location = new Point(20, 150);

Controls.Add(dynamicButton);

read.Close();

Answer

You must call .Read() at least once when using a DataReader, also things like SqlDataReader and SqlConnection should really be inside a using statement.

SqlCommand command = new SqlCommand("select * from button_properties", con);
con.Open();
using(SqlDataReader read = command.ExecuteReader())
{
    while(read.Read())
    {
        Button dynamicButton = new Button();

        dynamicButton.Height = (int)read["height"];
        dynamicButton.Width = (int)read["width"];
        dynamicButton.Text = read["text"].ToString();
        dynamicButton.Name = read["name"].ToString();
        dynamicButton.Location = new Point(20, 150);

        Controls.Add(dynamicButton);
    }
}

Now the code will add a button per row in button_properties.