我有我認爲我初始化一些成員的用戶控件:爲什麼我的UserControl不能保持其初始化?
// 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
}
// .........
}
}
當我插入這個控制到我的主要形式,雖然和調用內MyUserControl
檢查值的功能,事情並不像他們正在初始化:
// 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());
}
}
}
我猜這是一個真正簡單錯誤,但我不知道在哪裏。我已經嘗試過預先添加this.
,但這可能不是固定代碼的方法。 :)
一如既往的感謝!
編輯: Pete建議您進入設計器代碼,告訴我寫入過程發生在哪裏。首先我調用用戶控件的構造函數,然後再用默認值覆蓋這些值。我沒有指定任何默認值(Sanjeevakumar Hiremath的建議),所以默認值是原始類型的默認值(對於int
,這是0)。
'私人字符串m_myInt控制這種行爲;',物業類型爲int。發佈編碼並重現問題的代碼。 – 2011-04-04 22:01:11
你的設計器代碼是什麼樣的?你是否在你的UC構造函數代碼中設置了一個斷點,以查看什麼時候碰到和什麼時候出現? – 2011-04-04 22:02:08
@Hans:對不起!我將變量名稱更改爲通用事物,並忘記改變它。 – John 2011-04-04 22:02:48