Reputation: 23753
Since only some standard items (textBox etc.) can be added to a ToolStrip control at design time in a Winform app, I've added a DateTimePicker control dynamically as follows but I'm not sure how to access the datetime value of the selected date in the control
var datePicker = new ToolStripControlHost(new DateTimePicker());
toolStrip1.Items.Add(datePicker);
I've tried the following that still works as above but can't get access to the selected date value of the dateTimePicker added:
DateTimePicker myDateTimePicker = new DateTimePicker();
var datePicker = new ToolStripControlHost(myDateTimePicker);
toolStrip1.Items.Add(datePicker);
This MSDN tutorial describes how to add items dynamically to ToolStrip but nothing else.
Upvotes: 1
Views: 1481
Reputation: 125187
You can handle ValueChanged
event of the DateTimePicker
this way:
private void Form1_Load(object sender, EventArgs e)
{
var item = new ToolStripControlHost(new DateTimePicker());
((DateTimePicker)item.Control).ValueChanged += ToolStripDatePicker1_ValueChanged;
item.Name = "ToolStripDatePicker1";
toolStrip1.Items.Add(item);
}
private void ToolStripDatePicker1_ValueChanged(object sender, EventArgs e)
{
var datePicker = (DateTimePicker)sender;
MessageBox.Show(datePicker.Value.ToString());
}
Also as another option, you can find the DateTimePicker
control in another button click event handler this way:
private void toolStripButton1_Click(object sender, EventArgs e)
{
var item = ((ToolStripControlHost)this.toolStrip1.Items["ToolStripDatePicker1"]);
var datePicker = (DateTimePicker)item.Control;
MessageBox.Show(datePicker.Value.ToString());
}
Note: A better solution would be deriving from ToolStripControlHost
. This way you can expose properties and events which you need. For example, you can expose Value
property and ValueChanged
event of embedded DateTimePicker
control.
The MSDN example How to: Wrap a Windows Forms Control with ToolStripControlHost shows you how to create a custom control to host in ToolStrip
. You can simply use the example to create your custom ToolStripDateTimePicker
control.
Upvotes: 1