Search code examples
c#wpfdatabaselabelautocreate

C# WPF Autocreate Label from database


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)


Solution

  • 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++;
                }
            }