Datetimepicker is set but still shows up as empty

budtuck

New member
Joined
Aug 17, 2018
Messages
2
Programming Experience
1-3
Hello,

I have encountered a problem that is hard to explain. In a tabcontrol I programmatically add tabs and then in each tab I add Controls such as textboxes etc

The problem I have seen is with DateTimePickers. I add one in first tab, and then in second tab another one. In both tabs the dtp Control shows correct Text according to the dtp formatting. But when I try to get the Text values from each Control in each tab I will receive "" from the second tab (but not every time...). Using the dtp Control in second tab and manually set a value it will work.

If you would like to see this for yourself and try to figure out what's going on I would appreciate it:

Create a windows Project and add two buttons, one tabcontrol and one richtextbox. In designer remove the two default tabs and in Form1 add this simple code to reproduce:

C#:
public partial class Form1 : Form
    {
        int index = 0;
        public Form1()
        {
            InitializeComponent();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            tabControl1.TabPages.Add(index.ToString());
            DateTimePicker dtp = new DateTimePicker();
            dtp.Name = "dtp" + index;
            dtp.Parent = tabControl1.TabPages[index];
            dtp.Value = DateTime.Now.AddDays(-20);
            dtp.Format = DateTimePickerFormat.Custom;
            dtp.CustomFormat = "yyyyMMdd";
            index++;
        }
        private void button2_Click(object sender, EventArgs e)
        {
            foreach ( TabPage tabpage in tabControl1.TabPages)
            {
                foreach ( Control control in tabpage.Controls)
                {
                    richTextBox1.AppendText(tabpage.Text + ": " + control.Text + Environment.NewLine);
                }
            }
        }
    }

If I run this I get this result:


Skärmklipp.PNG


Can anyone expain if I am doing something wrong here or is this a strange bug? I am using
.Net framework 4.5.2
Microsoft Visual Studio Professional 2015
Version 14.0.25420.01 Update 3



/Bud
 
You can call Show method of the TabPage after it is added and it should work out. (this will not make it the selected tabpage)
 
When you add controls to a TabPage, they are not actually created until that TabPage is selected. That makes the TabControl a bit more efficient at startup but it means that making use of controls on potentially unselected pages is hazardous. Presumably calling the Show method that JohnH mentioned forces the creation of the child controls without having to select the TabPage.

That said, you almost certainly should not be using the Text property of a DateTimePicker anyway. You should pretty much always be using the Value property.
 

Latest posts

Back
Top Bottom