I'm trying to instantiate two pictureboxes created at runtime. I've assigned those to a panel, and I try to instantiate this in the form load event.
Here is my Class with the two pictureboxes and the panel:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Drawing;
namespace AudioNodeGUI.Klassen
{
public class DateiÖffnenUndAuswählenSteuerelement : Form
{
public int xLoc = 0;
public int yLoc = 0;
public Point loc1;
public Point loc2;
public Panel elementpanel;
public DateiÖffnenUndAuswählenSteuerelement()
{
this.loc1 = new Point(xLoc, yLoc);
this.loc2 = new Point(xLoc + 41, yLoc);
this.elementpanel = new Panel
{
Name = "elementpanel",
Size = new Size(154, 22),
Location = new Point(xLoc, yLoc),
};
}
public Panel Zeichnen()
{
PictureBox browseImage = new PictureBox()
{
Name = "browseimage",
Size = new Size(41, 22),
Location = loc1,
Image = Image.FromFile(#"F:\AudioNodeGUI\images\Browse_used_files.jpg"),
Visible = true,
};
PictureBox fileImage = new PictureBox()
{
Name = "fileimage",
Size = new Size(113, 22),
Location = loc2,
Image = Image.FromFile(#"F:\AudioNodeGUI\images\Filebutton1.jpg"),
Visible = true,
};
browseImage.Click += new EventHandler(browseImage_Clicked);
fileImage.Click += new EventHandler(fileImage_Clicked);
this.elementpanel.Controls.Add(browseImage);
this.elementpanel.Controls.Add(fileImage);
return elementpanel;
}
public void browseImage_Clicked(object sender, System.EventArgs e)
{
}
public void fileImage_Clicked(object sender, System.EventArgs e)
{
OpenFileDialog open = new OpenFileDialog();
open.Filter = "Audio Files(*.wav; *.mp3; *.aif; *.aiff)";
}
}
}
And in the form load event, I've tried to instantiate the custom control:
private void AudioNodeWindow_Load(object sender, EventArgs e)
{
AudioNodeGUI.Klassen.DateiÖffnenUndAuswählenSteuerelement element = new AudioNodeGUI.Klassen.DateiÖffnenUndAuswählenSteuerelement();
Panel panel = element.Zeichnen();
this.Controls.Add(panel);
}
But when I ran the programm, the control wasn't shown. Do you know where i have a mistake?
Related
In the code below, I tried to display a popup above the button when the button is pressed, but the AutoSize of ToolStripControlHost does not work properly and the entire contents are not displayed.
In addition to that, the popup is displayed slightly above the button, even though the button location is specified.
How can I solve this problem?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp7
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var panel1 = new Panel();
var label1 = new Label();
label1.Text = "12345\nabsde\nlllllllllllllllllA\nVWXYZ\nZZZZZZZZZZZZZZA";
label1.BackColor = Color.Red;
label1.Margin = Padding.Empty;
label1.AutoSize = true;
label1.Size = Size.Empty;
label1.Location = new Point(0, 0);
panel1.Controls.Add(label1);
var toolStripControlHost = new ToolStripControlHost(panel1);
toolStripControlHost.Margin = Padding.Empty;
toolStripControlHost.Padding = Padding.Empty;
toolStripControlHost.BackColor = SystemColors.Info;
toolStripControlHost.AutoSize = true;
toolStripControlHost.Size = Size.Empty;
var toolStripDropDown = new ToolStripDropDown();
toolStripDropDown.Margin = Padding.Empty;
toolStripDropDown.Padding = Padding.Empty;
toolStripDropDown.DropShadowEnabled = false;
toolStripDropDown.AutoSize = true;
toolStripDropDown.Size = Size.Empty;
toolStripDropDown.Items.Add(toolStripControlHost);
toolStripDropDown.Show(this, button1.Location, ToolStripDropDownDirection.AboveRight);
}
}
}
I noticed that the font changes when a control is inserted into toolStripControlHost, so I inserted the following code to try it out and make the font explicit, and it works fine now.
toolStripControlHost.Font = DefaultFont;
In the following code, C# and js are linked together and ToolStripDropDown is used to create a popup, but the mouseleave event of js does not fire when the mouse leaves the HTML element.
However, when I move the mouse over the popup, the mouseleave event fires.
If you move the mouse away from other directions, the mouseleave event will not fire.
Also, it seems to fire when the popup is not shown on the C# side.
I tried writing a code to focus on the WebBrowser control after Show, but even so, mouseleave of js doesn't fire.
I wonder why this is.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp5
{
public partial class Form1 : Form
{
public ToolStripDropDown toolStripDropDown;
public Form1()
{
InitializeComponent();
toolStripDropDown = new ToolStripDropDown();
toolStripDropDown.Margin = Padding.Empty;
toolStripDropDown.Padding = Padding.Empty;
toolStripDropDown.DropShadowEnabled = false;
webBrowser1.ObjectForScripting = new TestClasss(this);
webBrowser1.DocumentText = #"<script>
window.onload = function() {
var elm = document.createElement('div');
elm.innerHTML = 'test';
document.body.appendChild(elm);
elm.onmouseover = function() {
window.external.ShowPopup(this.getBoundingClientRect().left, this.getBoundingClientRect().top);
};
elm.onmouseleave = function()
{
window.external.ClosePopup();
};
};
</script>";
}
}
[ComVisible(true)]
public class TestClasss
{
private Form1 viewer;
public TestClasss(Form1 viewer)
{
this.viewer = viewer;
}
public void ShowPopup(int x, int y)
{
var panel1 = new Panel();
panel1.BackColor = Color.Red;
var label1 = new Label();
label1.Text = "popup";
panel1.Controls.Add(label1);
var toolStripControlHost = new ToolStripControlHost(panel1);
toolStripControlHost.Margin = Padding.Empty;
toolStripControlHost.Padding = Padding.Empty;
viewer.toolStripDropDown.Items.Clear();
viewer.toolStripDropDown.Items.Add(toolStripControlHost);
viewer.toolStripDropDown.Show(viewer.webBrowser1, new Point(x, y), ToolStripDropDownDirection.AboveRight);
}
public void ClosePopup()
{
viewer.toolStripDropDown.Close();
}
}
}
Try this code
Using System;
Using System.Collections.Generic;
Using System.ComponentModel;
Using System.Data;
Using System.Drawing;
Using System.Text;
Using System.Windows.Forms;
namespace WindowsApplication1
{
public partial class Form5 : Form
{
public Form5()
{
InitializeComponent();
webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted);
}
void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
webBrowser1.Document.Body.MouseOver += new HtmlElementEventHandler(Body_MouseOver);
}
void Body_MouseOver(object sender, HtmlElementEventArgs e)
{
if (e.ToElement != null && e.ToElement.TagName == "H1" && e.ToElement.GetAttribute("processed") != "true")
{
string[] words = e.ToElement.InnerHtml.Split(' ');
e.ToElement.InnerHtml = "";
for (int i = 0; i < words.Length; i++)
e.ToElement.InnerHtml += "<span> " + words[i] + " </span>";
foreach (HtmlElement el in e.ToElement.GetElementsByTagName("span"))
el.MouseOver += new HtmlElementEventHandler(e_MouseOver);
e.ToElement.SetAttribute("processed", "true");
}
}
void e_MouseOver(object sender, HtmlElementEventArgs e)
{
toolStripTextBox1.Text = e.ToElement.InnerText;
}
}
First post on this wonderful site so feedback is greatly appreciated.
I followed a video instruction on Youtube by one of the NAV guru about consuming web services using C#. I was able to replicate what he did in Sandbox, but now that I want to implement in Live it's a hit or miss type of ordeal. If I made a small change somewhere the WS stopped working then after tweaking it here and there all of a sudden it works, then the cycle continues.
I basically created a form with two datagrids, one for sales header and one for sales line, with 3 buttons for New Order, New Line, and Save. Below is my code. Can you point me in the right direction as to:
1. Why my code is not working?
2. Why it works and then stops working? What to watch out for?
3. In my original code, using System.Data is not showing an error. I had to comment it out on this form because it has the scribbly line underneath. How come?
I am a noob to web services and C# in general. Thanks in advance for your help.
using System;
using System.Collections.Generic;
using System.ComponentModel;
//using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using SalesOrderXML.ServiceReference3;
using System.ServiceModel;
using System.Net;
namespace SalesOrderXML
{
public partial class Form2 : Form
{
private Sales saleslive = new Sales();
private SalesOrderService_PortClient svc1;
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
//BasicHttpBinding SalesOrderService_Binding = new BasicHttpBinding();
//SalesOrderService_Binding.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly;
//SalesOrderService_Binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows;
var binding = new System.ServiceModel.BasicHttpBinding();
binding.Security.Mode = System.ServiceModel.BasicHttpSecurityMode.TransportCredentialOnly;
binding.Security.Transport.ClientCredentialType = System.ServiceModel.HttpClientCredentialType.Windows;
svc1 = new SalesOrderService_PortClient(
//SalesOrderService_Binding, new EndpointAddress("http://localhost:7047/DynamicsNAV/WS/Cronus%20-%20LIVE%20COMPANY/Codeunit/SalesOrderService"));
binding, new EndpointAddress("http://localhost:7047/DynamicsNAV/WS/Cronus%20-%20LIVE%20COMPANY/Codeunit/SalesOrderService"));
svc1.ClientCredentials.Windows.ClientCredential = new NetworkCredential("testuser", "password123", "localhost");
svc1.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Delegation;
//SalesOrderService_Binding.MaxReceivedMessageSize = 99999999;
binding.MaxReceivedMessageSize = 99999999;
binding.MaxBufferSize = 99999999;
saleslive = new Sales();
LoadData();
}
private void dataGridView3_RowEnter(object sender, DataGridViewCellEventArgs e)
{
var orderlive = saleslive.Order[e.RowIndex];
dataGridView4.DataSource = orderlive.Line;
}
private void LoadData()
{
svc1.ReadSalesOrders(ref saleslive);
dataGridView3.DataSource = saleslive.Order;
}
private void SaveData()
{
svc1.SaveSalesOrders(saleslive);
//dataGridview3.DataSource = saleslive.Order;
}
private void button3_Click(object sender, EventArgs e)
{
svc1.SaveSalesOrders(saleslive);
LoadData();
}
private void button1_Click(object sender, EventArgs e)
{
var orderlive = saleslive.Order;
orderlive[orderlive.Count() - 1] = new Order { Line = new Line[] { } };
Array.Resize(ref orderlive, saleslive.Order.Count() + 1);
saleslive.Order = orderlive;
dataGridView3.DataSource = saleslive.Order;
}
private void dataGridView4_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
var orderlive = saleslive.Order[dataGridView3.CurrentRow.Index];
var line = orderlive.Line;
if (line == null)
{
line = new Line[] { };
}
Array.Resize(ref line, line.Count() + 1);
line[line.Count() - 1] = new Line
{
LineDocType = "Order",
LineDocNo = "",
LineNo = (line.Count() * 10000).ToString(),
Type = "Item",
SKU = "0316",
Quantity = "10",
Price = "1200",
Amount = "12000",
LineTotal = "12000"
};
orderlive.Line = line;
dataGridView4.DataSource = line;
}
}
}
Im trying to write this simple winform menu and I need to add the contents of the NBox text box to a string so I can display it when a button is pressed, however I keep getting the error that NBox does not exist in the current context. So, how would i got about making the contents of the text box available at the press of a button?
using System;
using System.Windows.Forms;
using System.Drawing;
using System.Diagnostics;
//namespace game{
class MainM : Form{
public MainM(){
Text = "Adventures Main Menu";
Size = new Size(400,400);
//NameBox
TextBox NBox = new TextBox();
NBox.Location = new Point(145, 100);
NBox.Size = new Size(200, 30);
//Title Label
Label title = new Label();
title.Text = "ADVENTURE THE GAME";
title.Location = new Point(145, 30);
title.Size = new Size(200,60);
title.Font = new Font(defaultFont.FontFamily, defaultFont.Size, FontStyle.Bold);
//The main menu Buttons and all that jazz
Button credits = new Button();
Button start = new Button();
//Credits Button
credits.Text = "Credits";
credits.Size = new Size(75,20);
credits.Location = new Point(145,275);
credits.Click += new EventHandler(this.credits_button_click);
//Start Button
start.Text = "Start";
start.Size = new Size(75,20);
start.Location = new Point(145,200);
start.Click += new EventHandler(this.start_button_click);
//Control addition
this.Controls.Add(title);
this.Controls.Add(credits);
this.Controls.Add(start);
this.Controls.Add(NBox);
}
public void test(){
//The Main Window
}
private void credits_button_click(object sender, EventArgs e){
MessageBox.Show("Created by: Me");
}
private void start_button_click(object sender, EventArgs e){
this.Hide();
string name = NBox.Text;
MessageBox.Show(name);
//Process.Start("TextGame.exe");
}
public static void Main(){
Application.Run(new MainM());
}
}
//}
First, you need to name the control, that name will be its key in container's Controls collection :
//NameBox
TextBox NBox = new TextBox();
NBox.Location = new Point(145, 100);
NBox.Size = new Size(200, 30);
NBox.Name = "NBox"; //Naming the control
Then you will be able to retrieve it from the container:
private void start_button_click(object sender, EventArgs e){
this.Hide();
TextBox NBox= (TextBox)Controls.Find("NBox", true)[0];//Retrieve controls by name
string name = NBox.Text;
MessageBox.Show(name);
//Process.Start("TextGame.exe");
}
You declared NBox in consturctor and it is visible only inside constructor. You need to move it outside of constructor.
using System;
using System.Windows.Forms;
using System.Drawing;
using System.Diagnostics;
//namespace game{
class MainM : Form{
TextBox NBox;
public MainM(){
Text = "Adventures Main Menu";
Size = new Size(400,400);
//NameBox
NBox = new TextBox();
...
I have this code to create and show a form with monthcalendar control on it.
private void showcalendar_Click(object sender, EventArgs e)
{
ShowCalendar();
}
void ShowCalendar()
{
DateTime current5 = DateTime.Now.AddDays(-5);
MonthCalendar cal = new MonthCalendar();
Panel panel = new Panel();
Form f = new Form();
cal.MaxSelectionCount = 1;
cal.SetDate(current5);
cal.DateSelected += new DateRangeEventHandler(DateSelected);
cal.ShowToday = true;
panel.Width = cal.Width;
panel.Height = cal.Height;
panel.BorderStyle = BorderStyle.FixedSingle;
panel.Controls.Add(cal);
f.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
f.ShowInTaskbar = false;
f.Size = panel.Size;
f.Location = MousePosition;
f.StartPosition = FormStartPosition.Manual;
f.Controls.Add(panel);
f.Deactivate += delegate { f.Close(); };
f.Show();
}
void DateSelected(object sender, DateRangeEventArgs e)
{
MonthCalendar cal = (MonthCalendar)sender;
Form f = cal.FindForm();
f.Close();
}
When I invoke ShowCalendar monthcalendar control is displayed and I can select date within it. The problem is that when I click on a certain area(the lowest one with current date depicted) I'm getting an exception - "Cannot access a disposed object. Object name: 'MonthCalendar'." I don't know how this exception arises at all and how to get rid of it. Maybe you have any thoughts?
My application is not multithreaded, just simple form with a button which invokes ShowCalendar function.
An interesting problem: the only way I could find to make it work is to keep the popup form as a property of the Main form and use Hide() instead of Close().
public partial class Form1 : Form
{
Form f = new Form();
public Form1()
{
InitializeComponent();
}
private void showcalendar_Click(object sender, EventArgs e)
{
ShowCalendar();
}
void ShowCalendar()
{
DateTime current5 = DateTime.Now.AddDays(-5);
MonthCalendar cal = new MonthCalendar();
Panel panel = new Panel();
cal.MaxSelectionCount = 1;
cal.SetDate(current5);
cal.DateSelected += new DateRangeEventHandler(DateSelected);
cal.ShowToday = true;
panel.Width = cal.Width;
panel.Height = cal.Height;
panel.BorderStyle = BorderStyle.FixedSingle;
panel.Controls.Add(cal);
f.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
f.ShowInTaskbar = false;
f.Size = panel.Size;
f.Location = MousePosition;
f.StartPosition = FormStartPosition.Manual;
f.Controls.Add(panel);
f.Deactivate += delegate { f.Hide(); };
f.Show();
}
void DateSelected(object sender, DateRangeEventArgs e)
{
DateTime selection = e.Start;
Console.WriteLine("Selected: {0}", selection.ToLongDateString());
this.Activate(); // Forces popup to de-activate
}
}
Workaround to this: remove MonthCalendar from it's parent before closing the form that hosts this MonthsCalendar. So the change is to add line cal.Parent.Controls.Remove(cal).
The DateSelected method becomes:
void DateSelected(object sender, DateRangeEventArgs e)
{
MonthCalendar cal = (MonthCalendar)sender;
Form f = cal.FindForm();
cal.Parent.Controls.Remove(cal);
f.Close();
}
I have a quick solution in 3 steps.
Fixes and enhancements:
Rectangle dynamic size fixed under different versions of windows.
Validate if principal form is topmost.
Unload calendar form from memory without bug.
Good behavior between MonthCalendar and MaskedTextBox controls
Steps:
1) Create a new windows forms application, view code in form1 and replace all text with this:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Globalization;
using System.Threading;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
private System.Windows.Forms.CheckBox chkShowWeeksNumbers;
private System.Windows.Forms.CheckBox chkThisFormTopMost;
private System.Windows.Forms.MaskedTextBox maskedInputBox;
private System.Windows.Forms.Button btnShowFloatingCalendar;
public Form1()
{
this.chkShowWeeksNumbers = new System.Windows.Forms.CheckBox();
this.chkThisFormTopMost = new System.Windows.Forms.CheckBox();
this.maskedInputBox = new System.Windows.Forms.MaskedTextBox();
this.btnShowFloatingCalendar = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// chkShowNumbersOfWeeks
//
this.chkShowWeeksNumbers.AutoSize = true;
this.chkShowWeeksNumbers.Location = new System.Drawing.Point(18, 116);
this.chkShowWeeksNumbers.Name = "chkShowWeeksNumbers";
this.chkShowWeeksNumbers.Size = new System.Drawing.Size(137, 17);
this.chkShowWeeksNumbers.TabIndex = 1;
this.chkShowWeeksNumbers.Text = "Show number of weeks";
this.chkShowWeeksNumbers.UseVisualStyleBackColor = true;
//
// chkThisFormTopMost
//
this.chkThisFormTopMost.AutoSize = true;
this.chkThisFormTopMost.Location = new System.Drawing.Point(18, 139);
this.chkThisFormTopMost.Name = "chkThisFormTopMost";
this.chkThisFormTopMost.Size = new System.Drawing.Size(124, 17);
this.chkThisFormTopMost.TabIndex = 2;
this.chkThisFormTopMost.Text = "This form TopMost";
this.chkThisFormTopMost.UseVisualStyleBackColor = true;
this.chkThisFormTopMost.CheckedChanged += new EventHandler(chkThisFormTopMost_CheckedChanged);
//
// maskedInputBox
//
this.maskedInputBox.Location = new System.Drawing.Point(18, 53);
this.maskedInputBox.Mask = "00/00/0000 00:00";
this.maskedInputBox.Name = "maskedInputBox";
this.maskedInputBox.Size = new System.Drawing.Size(115, 20);
this.maskedInputBox.TabIndex = 3;
this.maskedInputBox.ValidatingType = typeof(System.DateTime);
//
// btnShowFloatingCalendar
//
this.btnShowFloatingCalendar.Location = new System.Drawing.Point(139, 49);
this.btnShowFloatingCalendar.Name = "btnShowFloatingCalendar";
this.btnShowFloatingCalendar.Size = new System.Drawing.Size(65, 27);
this.btnShowFloatingCalendar.TabIndex = 4;
this.btnShowFloatingCalendar.Text = "Calendar";
this.btnShowFloatingCalendar.UseVisualStyleBackColor = true;
this.btnShowFloatingCalendar.Click += new EventHandler(btnShowFloatingCalendar_Click);
//
// Form1
//
this.Controls.Add(this.btnShowFloatingCalendar);
this.Controls.Add(this.maskedInputBox);
this.Controls.Add(this.chkThisFormTopMost);
this.Controls.Add(this.chkShowWeeksNumbers);
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
//DateTime format using in United States
//More info: http://msdn.microsoft.com/en-us/library/system.globalization.cultureinfo%28v=vs.71%29.aspx
// http://msdn.microsoft.com/en-us/library/5hh873ya.aspx
Thread.CurrentThread.CurrentCulture = new CultureInfo(0x0409);
CultureInfo cultureInfoUSA = new CultureInfo(0x0409, false);
this.maskedInputBox.Culture = cultureInfoUSA;
}
//Constructor
clsMonthCalendarBehavior userCalendar = new clsMonthCalendarBehavior();
private void btnShowFloatingCalendar_Click(object sender, EventArgs e)
{
userCalendar.ShowCalendar(this.maskedInputBox,
this.chkShowWeeksNumbers.Checked,
this.chkThisFormTopMost.Checked);
}
private void chkThisFormTopMost_CheckedChanged(object sender, EventArgs e)
{
this.TopMost = this.chkThisFormTopMost.Checked;
}
}
}
2) Add new class item into project and named clsMonthCalendarBehavior.cs, later replace all text with this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
namespace WindowsFormsApplication1
{
class clsMonthCalendarBehavior
{
private bool manualDateTimeIsDone
{
get
{
return (SetDateTimeManual(this._dateTimeInput.Text));
}
}
private static DateTime dateTimeManual;
//Determine if the user inserting a correctly date and time
internal static bool SetDateTimeManual(string inputReference)
{
DateTime newDateTime = new DateTime(2000, 1, 1, 0, 0, 0);
bool isDateTime = DateTime.TryParse(inputReference, out newDateTime);
if (isDateTime)
dateTimeManual = newDateTime;
return (isDateTime ? true : false);
}
private MaskedTextBox _dateTimeInput;
internal void ShowCalendar(MaskedTextBox dateTimeInput,
bool showNumbersOfWeeks,
bool principalFormIsTopMost)
{
MonthCalendar monthCalendarCustomized = new MonthCalendar();
Panel popupPanel = new Panel();
Form floatingForm = new Form();
this._dateTimeInput = dateTimeInput;
//OPTIONAL: Show week numbers
monthCalendarCustomized.ShowWeekNumbers = showNumbersOfWeeks;
monthCalendarCustomized.MaxSelectionCount = 1;
if (manualDateTimeIsDone)
monthCalendarCustomized.SetDate(dateTimeManual); //User, date and time selected
else
monthCalendarCustomized.SetDate(DateTime.Now); //System, actual date and time
monthCalendarCustomized.DateSelected += new DateRangeEventHandler(DateSelected);
monthCalendarCustomized.KeyDown +=new KeyEventHandler(KeyDown);
monthCalendarCustomized.ShowToday = true;
//IDEA: bolded dates about references, etc.
monthCalendarCustomized.BoldedDates = new DateTime[]
{
DateTime.Today.AddDays(1),
DateTime.Today.AddDays(2),
DateTime.Today.AddDays(7),
DateTime.Today.AddDays(31),
DateTime.Today.AddDays(10)
};
popupPanel.BorderStyle = BorderStyle.FixedSingle;
popupPanel.Controls.Add(monthCalendarCustomized);
floatingForm.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
floatingForm.ShowInTaskbar = false;
floatingForm.Location = Control.MousePosition;
floatingForm.StartPosition = FormStartPosition.Manual;
floatingForm.Controls.Add(popupPanel);
floatingForm.Deactivate += delegate { floatingForm.Close(); };
//NOTE: if principal from is topmost, cannot show in front "floatingForm" with calendar
// this option fix the situation.
floatingForm.TopMost = principalFormIsTopMost;
//NOTE: set initial size of controls.
floatingForm.Size = popupPanel.Size = new Size(20, 20);
floatingForm.Show();
popupPanel.Size = floatingForm.Size = monthCalendarCustomized.Size;
popupPanel.Width = popupPanel.Width + 2;
popupPanel.Height = popupPanel.Height + 2;
floatingForm.Width = floatingForm.Width + 3;
floatingForm.Height = floatingForm.Height + 3;
}
void DateSelected(object sender, DateRangeEventArgs e)
{
//Set data selected with culture info mask
this._dateTimeInput.Text = SetTimeValue(e.Start).ToString("MM/dd/yyyy HH:mm");
CloseFloatingForm(sender);
}
private static void CloseFloatingForm(object sender)
{
MonthCalendar monthCalendarCustomized = (MonthCalendar)sender;
Form floatingForm = monthCalendarCustomized.FindForm();
monthCalendarCustomized.Parent.Controls.Remove(monthCalendarCustomized);
floatingForm.Close();
}
private DateTime SetTimeValue(DateTime selectedDateTime)
{
//Recovery time of after selection, because when user select a new date
//Month Calendar reset the time
if (manualDateTimeIsDone)
{
TimeSpan addTimeValue = new TimeSpan(dateTimeManual.Hour,
dateTimeManual.Minute,
dateTimeManual.Second);
selectedDateTime = selectedDateTime.Add(addTimeValue);
}
return (selectedDateTime);
}
private void KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Escape)
CloseFloatingForm(sender);
}
}
}
3) Run and test.
I think the problem is that you close the form in which the month calendar is contained, which makes your control disposed.
Interesting. I can reproduce this just fine here (running in VS 2008, target 3.5). There's quite a lot of noise in the code, the following causes the same behavior here, that is
Selecting any date by clicking on the day/number works
Selecting the "today" area at the bottom results in the ObjectDisposedException
Reduced/minimal complete test:
using System;
using System.Windows.Forms;
namespace Test
{
public class Form1 : Form
{
public Form1()
{
var dateSelectionButton = new Button();
SuspendLayout();
dateSelectionButton.Text = "Pick Date";
dateSelectionButton.Click += (SelectDateClick);
Controls.Add(dateSelectionButton);
ResumeLayout();
}
private void SelectDateClick(object sender, EventArgs e)
{
MonthCalendar cal = new MonthCalendar();
Form f = new Form();
cal.DateSelected += DateSelected;
f.Controls.Add(cal);
f.Show();
}
void DateSelected(object sender, DateRangeEventArgs e)
{
MonthCalendar cal = (MonthCalendar)sender;
Form f = cal.FindForm();
f.Close();
}
}
}