I have a UserControl for which I think I’m initializing some of the members:
// MyUserControl.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace MyNamespace
{
public partial class MyUserControl : UserControl
{
private string m_myString;
private int m_myInt;
public string MyString
{
get { return m_myString; }
set { m_myString = value; }
}
public int MyInt
{
get { return m_myInt; }
set { m_myInt = value; }
}
public MyUserControl()
{
InitializeComponent();
MyString = ""; // was null, now I think it's ""
MyInt = 5; // was 0, now I think it's 5
}
// .........
}
}
When I insert this control into my main form, though, and call a function that checks values within MyUserControl, things don’t look like they’re initialized:
// MainForm.cs
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;
namespace MyProgram
{
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
}
private void MyButton_Click(object sender, EventArgs e)
{
// this prints 0 rather than 5
MessageBox.Show(this.theUserControl.MyInt.ToString());
}
}
}
I’m guessing this is a really simple error but I don’t know where. I’ve tried prepending this. to things, but this probably isn’t the way to go about fixing code. 🙂
Thanks as always!
EDIT: Stepping into the designer code as Pete suggested showed me where the write-over was happening. First I called the constructor of the user control, and then later, the values got overwritten with default values. I hadn’t specified any default values (Sanjeevakumar Hiremath’s suggestion) so the default values were those of the primitive types (for int this was 0).
What you’re likely seeing here is an artifact of the designer. If you ever opened up
MainFormin a designer after you addedMyUserControlit likely recorded the default values ofMyUserControlin the generatedInitializeComponentmethod ofMainForm. These recorded values are re-assigned after the constructor ofMyUserControlruns hence they’re overwriting the values you set.You can control this behavior via the use of the
DesignerSerializationVisibilityAttribute