0

I want to auto create label from database. For ex. I have table [workers] with columns [id][name][sname] etc. When i create new worker i want application to create new Label with his name/sname etc.

I tried binding label manualy but this is not the point.

              label1.Text = dt.Rows[0]["Worker_Name"].ToString()

Yeah, i know its not from wpf.

In the last step i want drag&drop app where i will drag&drop workers(label) to new sections, new learders etc but this will be in the future:) (sorry for my english)

Kafus
  • 61
  • 1
  • 14

1 Answers1

1

EDIT

A WPF solution will be treated differently. This is how I have done it. A DataGrid's ItemSource will be bound and DataContext set in the code behind to an ObservableCollection.

So if you wanted to create labels for all entries in your grid you would iterate through the ObservableCollection and instantiate a new label and set the properties from data in the ObservableCollection. If you want to create the label when the user clicks on an entry in the DataGrid I would do the following (modified from some other code !).

XAML

                        <DataGridTextColumn Binding="{Binding BackR, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
                                                    Header="R" Width="40"/>

                        <DataGridTextColumn Binding="{Binding BackG, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
                                                    Header="G" Width="40"/>

                        <DataGridTextColumn Binding="{Binding BackB, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
                                                    Header="B" Width="40"/>

                        <DataGridTextColumn Binding="{Binding Tags, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
                                                    Header="Tags" Width="90"/>

                    </DataGrid.Columns>
                </DataGrid>

In The Model

private ObservableCollection<PaletteEntry> _paletteEntries = new  ObservableCollection<PaletteEntry>();

public ObservableCollection<PaletteEntry> PaletteEntries
{
    get { return _paletteEntries; }
    set { _paletteEntries = value; OnPropertyChanged("PaletteEntries"); }
}

public class PaletteEntry : INotifyPropertyChanged
    {
        private string _count;
        public string Count
        {
            get { return _count; }
            set
            {
                _count = value;
                if (PropertyChanged != null)
                    PropertyChanged(this, new PropertyChangedEventArgs("Count"));
            }
        }

        private string _readOnly;
        public string ReadOnly
        {
            get { return _readOnly; }
            set
            {
                _readOnly = value;
                if (PropertyChanged != null)
                    PropertyChanged(this, new PropertyChangedEventArgs("ReadOnly"));
            }
        }

        private string _displayPalletteType;
        public string DisplayPalletteType
        {
            get { return _displayPalletteType; }
            set
            {
                _displayPalletteType = value;
                if (PropertyChanged != null)
                    PropertyChanged(this, new PropertyChangedEventArgs("DisplayPalletteType"));
            }
        }

        private string _title;
        public string Title
        {
            get { return _title; }
            set
            {
                _title = value;
                if (PropertyChanged != null)
                    PropertyChanged(this, new PropertyChangedEventArgs("Title"));
            }
        }

        private SolidColorBrush _background;
        public SolidColorBrush Background
        {
            get { return _background; }
            set
            {
                _background = value;
                if (PropertyChanged != null)
                    PropertyChanged(this, new PropertyChangedEventArgs("Background"));
            }
        }

        private string _backname;
        public string BackName
        {
            get { return _backname; }
            set
            {
                _backname = value;
                if (PropertyChanged != null)
                    PropertyChanged(this, new PropertyChangedEventArgs("BackName"));
            }
        }

        private string _backR;
        public string BackR
        {
            get { return _backR; }
            set
            {
                _backR = value;
                if (PropertyChanged != null)
                    PropertyChanged(this, new PropertyChangedEventArgs("BackR"));
            }
        }

        private string _backG;
        public string BackG
        {
            get { return _backG; }
            set
            {
                _backG = value;
                if (PropertyChanged != null)
                    PropertyChanged(this, new PropertyChangedEventArgs("BackG"));
            }
        }

        private string _backB;
        public string BackB
        {
            get { return _backB; }
            set
            {
                _backB = value;
                if (PropertyChanged != null)
                    PropertyChanged(this, new PropertyChangedEventArgs("BackB"));
            }
        }

        private SolidColorBrush _foreground;
        public SolidColorBrush Foreground
        {
            get { return _foreground; }
            set
            {
                _foreground = value;
                if (PropertyChanged != null)
                    PropertyChanged(this, new PropertyChangedEventArgs("Foreground"));
            }
        }

        private string _forename;
        public string ForeName
        {
            get { return _forename; }
            set
            {
                _forename = value;
                if (PropertyChanged != null)
                    PropertyChanged(this, new PropertyChangedEventArgs("ForeName"));
            }
        }

        private string _foreR;
        public string ForeR
        {
            get { return _foreR; }
            set
            {
                _foreR = value;
                if (PropertyChanged != null)
                    PropertyChanged(this, new PropertyChangedEventArgs("ForeR"));
            }
        }

        private string _foreG;
        public string ForeG
        {
            get { return _foreG; }
            set
            {
                _foreG = value;
                if (PropertyChanged != null)
                    PropertyChanged(this, new PropertyChangedEventArgs("ForeG"));
            }
        }

        private string _foreB;
        public string ForeB
        {
            get { return _foreB; }
            set
            {
                _foreB = value;
                if (PropertyChanged != null)
                    PropertyChanged(this, new PropertyChangedEventArgs("ForeB"));
            }
        }

        private string _tags;
        public string Tags
        {
            get { return _tags; }
            set
            {
                _tags = value;
                if (PropertyChanged != null)
                    PropertyChanged(this, new PropertyChangedEventArgs("Tags"));
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected void NotifyPropertyChange(string propertyName)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    };

In the Code Behind

WindowsColorPallete.DataContext = null;
WindowsColorPallete.DataContext = viewModel.PaletteEntries;

private void WindowsColorPallete_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
    {
        if (!WindowsColorPallete.IsReadOnly)
            return;

        DependencyObject dep = (DependencyObject)e.OriginalSource;

        while ((dep != null) && !(dep is DataGridCell) && !(dep is DataGridColumnHeader))
        {
            dep = VisualTreeHelper.GetParent(dep);
        }

        if (dep == null)
            return;

        if (dep is DataGridCell)
        {
            DataGridCell cell = dep as DataGridCell;

            while ((dep != null) && !(dep is DataGridRow))
            {
                dep = VisualTreeHelper.GetParent(dep);
            }

            DataGridRow row = dep as DataGridRow;

            var ple = (ColorPickerViewModel.PaletteEntry)row.Item;
            currentPaletteEntry = ple;

            // HERE AS AN EXAMPLE IS WHERE I WOULD INSTANTIATE A NEW LABEL AND SET THE PROPERTIES
            // FROM THE ObservableCollection 
            // EG
            var l = new Label();
            l.Content = ple.Title;

            // ETC :) 

            if (ple.Title != "")
                TitleValue.Text = ple.Title;

            if (ple.Tags != "")
                TagsValue.Text = ple.Tags;

        }
    }

I think I understand what you want to achieve. This is from some old C# code I wrote ages ago. I loaded a datagridview up with the data and then iterated through it thus creating labels as needed. As you can see it adds the new labels and a new RichTextBox to a container, the panel and sets property data based on information in the datagrid. It also managed the positioning.

Hope I have understood what you wanted and this helps.
Jim

        for (int i = 0; i < dgv_Fields.Rows.Count; i++)
        {
            // Add a key field column that has NOT been selected to a column

            if (Convert.ToBoolean(dgv_Fields.Rows[i].Cells[0].Value) ||
                (Convert.ToInt32(dgv_Fields.Rows[i].Cells["Key#"].Value) > 0 &&
                !Convert.ToBoolean(dgv_Fields.Rows[i].Cells[0].Value)))
            {
                dgv_columns.ColumnCount = count + 1;
                cName = FirstLetterToUpper(dgv_Fields.Rows[i].Cells[1].Value.ToString());
                dgv_columns.Columns[count].Name = dgv_Fields.Rows[i].Cells[1].Value.ToString();

                if (Convert.ToInt32(dgv_Fields.Rows[i].Cells["Key#"].Value) > 0)
                    dgv_columns.Columns[count].Tag = dgv_Fields.Rows[i].Cells["Key#"].Value;
                else
                    dgv_columns.Columns[count].Tag = "";

                if ((Convert.ToInt32(dgv_Fields.Rows[i].Cells["Key#"].Value) > 0 &&
                !Convert.ToBoolean(dgv_Fields.Rows[i].Cells[0].Value)))
                    dgv_columns.Columns[count].Name = "*" + dgv_Fields.Rows[i].Cells[1].Value.ToString();

                tbx = x + 160;
                label = new Label();
                label.Name = "l" + count.ToString();
                label.Text = cName.PadRight(25);
                if ((Convert.ToInt32(dgv_Fields.Rows[i].Cells["Key#"].Value) > 0 &&
                !Convert.ToBoolean(dgv_Fields.Rows[i].Cells[0].Value)))
                    label.Text = "*" + cName.PadRight(25);
                label.Location = new Point(x, y);
                label.Font = new Font("Microsoft Sans Serif", 8, FontStyle.Bold);
                label.AutoSize = true;
                panel1.Controls.Add(label);

                richtextbox = new RichTextBox();
                richtextbox.Name = "rtb" + count.ToString();
                richtextbox.Location = new Point(tbx + 10, y - 4);
                richtextbox.Font = new Font("Microsoft Sans Serif", 8, FontStyle.Bold);
                richtextbox.Size = new Size(100, 35);
                richtextbox.Tag = count.ToString();
                richtextbox.Click += new EventHandler(richtextbox_Click);
                richtextbox.TextChanged += new EventHandler(richtextbox_TextChanged);
                panel1.Controls.Add(richtextbox);

                y += 40;
                count++;
            }
        }
Jim
  • 201
  • 2
  • 12
  • Thanks for the answer. I'll check this code tonight and i'll answer too :) anyway thanks a lot for help :) – Kafus Sep 22 '14 at 14:57
  • Thanks for helping me out. I think this is what i want :) But there is a problem with: (dgv_Fields.Rows[i].Cells[0].Value) because it's for C#. In WPF i can't use .Rows and .Cells. I read somewhere that .Rows = .Items but even if this is true there is .Cells and i dont have any idea what i have to do with this :( i think 'cName' doesn't exist too. What should i do? I can write it in C# but i want add drag&drop functions and i know that C# is poor for this. ( i read about this somewhere) – Kafus Sep 22 '14 at 16:26
  • can u share all code? there are some variables like tbx dgv_columns etc. that I can not assign :( – Kafus Sep 22 '14 at 19:08
  • Will look and see if I have a WPF version of the functionality, I think I have somwehere. – Jim Sep 22 '14 at 20:28
  • Thats will be awesome :) – Kafus Sep 22 '14 at 20:36
  • See my new answer. I have edited some other code I had with hopefully sufficient explanations. – Jim Sep 22 '14 at 22:40
  • Thats IS awesome :) now i just have little problems with: WindowsColorPallete Any namespace or assemble ref? The same is: set { _paletteEntries = value; OnPropertyChanged("PaletteEntries"); } OnPropertyChanged is highlighted. btw. is there any chance to bind data from my database? I can't see where i can add connectionstring – Kafus Sep 22 '14 at 23:39
  • silly to ask you about something else. Anyway u just made my day :) – Kafus Sep 22 '14 at 23:48
  • The model code is in the same namespace as the code behind for the xaml. Re the binding, I prefer to have a method that loads the data to the observable collection. Connection strings etc will depend on your database type but I would suggest using some ORM such as nHibernate or other. Then you can take advantage of the power of the binding to the datagrid. Changes to the collection are reflected into the grid. Also a user may not want changes to the data in the UI persisted straight away. If you are happy with all of this please flag my answer accordingly, thanks. – Jim Sep 23 '14 at 00:34