Dynamic Button is created in different Windows instead of creating in Stackpanel only

22 views Asked by At

Help. I want to create Dynamic buttons inside a stackpanel, I think I have a problem in my code This is my code:

        using (MySqlConnection conn = new MySqlConnection(constr))
        {
            conn.Open();

               using (MySqlDataAdapter adapter = new MySqlDataAdapter("SELECT GarmentName FROM tblthesis", conn))
            {
                ds = new DataSet();
                adapter.Fill(ds);

                foreach (DataRow dataRow in ds.Tables[0].Rows)
                {


                    Button button = new Button ();
                    button.Content = dataRow[0].ToString();

                    WindowTry winwin = new WindowTry();
                    winwin.sp.Children.Add(button);
                    winwin.Show();

Note, (sp) is the stackpanel of my windowTry window.

I have 5 datas in my database wherein I used that to name my buttons, but when I try to put that In WindowTry, and run it. It creates 5 windows with 1 button each, what should I do? please help.

2

There are 2 answers

0
alek kowalczyk On

You are creating for each DataRow a window, add a button to it, and show it, so it works just as it's implemented. You need to create the window before the loop, and show it after it.

            WindowTry winwin = new WindowTry();
            foreach (DataRow dataRow in ds.Tables[0].Rows)
            {
                Button button = new Button ();
                button.Content = dataRow[0].ToString();

                winwin.sp.Children.Add(button);
            }
            winwin.Show();
0
Alexander Bell On

You have to put these lines outside the foreach loop:

WindowTry winwin = new WindowTry();
foreach (DataRow dataRow in ds.Tables[0].Rows)
{ 
// the rest of your code
}
winwin.Show();