Saturday, April 20, 2013

Dynamically add multiple buttons to wpf grid?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Diagnostics;

namespace WpfApplication2
{
    /// 
    /// Interaction logic for MainWindow.xaml
    /// 
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            for (int i = 0; i < 10; i++)
            {
              g1.RowDefinitions.Add(new RowDefinition());
              g1.ColumnDefinitions.Add(new ColumnDefinition());
            }

            Button[] MyButtonList = new Button[100];
            int count = 0;

            for (int i = 0; i < 10; i++)
            {
                for (int j = 0; j < 10; j++)
                {
                  Button b = new Button()
                  {
                      Name = "btn" + i + j,
                      Content = "gan " + i + "" + j,
                      Tag = "tagg " + i + j
                  };
                  b.Click += new RoutedEventHandler(button_Click);

                  MyButtonList[count] = b;

                  g1.Children.Add(b);
                  Grid.SetRow(b, i);
                  Grid.SetColumn(b, j);

                  count++;
                }
            }

            // remove a button
            g1.Children.Remove(MyButtonList[97]);
        }

        void button_Click(object sender, RoutedEventArgs e)
        {
            //Debug.WriteLine("you clicked {0}", (sender as Button).Name);
            Debug.WriteLine("you clicked {0}", (sender as Button).Name, null);
            Debug.WriteLine(string.Format("you clicked {0}", (sender as Button).Name));
            Debug.WriteLine("you clicked " + (sender as Button).Name);
            Debug.Print("you clicked " + (sender as Button).Name);
            Debug.WriteLine("you clicked {0}", (sender as Button).Content);
            Debug.WriteLine("you clicked {0}", (sender as Button).Tag);

            //Window1 w1 = new Window1();
            //w1.ShowDialog();
        }
    }
}


No comments: