簡體   English   中英

在C#中,如何從派生類構造函數訪問派生類的屬性?

[英]In C# how do I access the properties of a derived class from the derived class constructor?

我有一個DataGridView派生的控件,其中定義了一些新屬性。 它們在屬性檢查器中按預期顯示並輸入了連接字符串值,但是當我編譯程序時,如果我在以下位置的構造函數上插入了一個中斷: if (ConnectionString == "" ) -它顯示ConnectionString為null,而connectionString確實為null 。 我意識到我應該在編寫完此代碼后對null進行測試,但要點是該屬性中包含字符串。

目的是將table和connectionString定義為從中填充表和屬性的屬性。 我究竟做錯了什么?

namespace ASControls
{

    public partial class ASDataGridView : DataGridView  
    {

        private string connectionString; 
        // Declares the property.
        [Description("Set the Connection String for the datbase concerned"),
        Category("Data")]
        public string ConnectionString
        {
           get { return connectionString; }
           set {connectionString= value; }
        }

        public ASDataGridView()
        {
        //
        // The InitializeComponent() call is required for Windows Forms designer support.
        //
        InitializeComponent();

        //
        // TODO: Add constructor code after the InitializeComponent() call.
        //

        if (ConnectionString == "" )
        {           
            MessageBox.Show("You must set the connection string in order to use an ASDataGridView control");
            return;
        } else {

            InitData(ConnectionString);
        }

        }
        ...

Simon談論的是在設計器中您無法調用數據庫的事實。 解決方案是:

if (IsInDesignMode) // Code runs in Blend --> create design time data.
{
    StatBarTextProp = "IN Design mode";
}
else // Code runs "for real"
{
    StatBarTextProp = /* Get from DB here*/ ;

}

現在,您的運行時很高興從數據庫中獲取內容,並且您的設計將具有默認設置。


是的,您可以在這里閱讀更多內容,但基本上是:

DesignerProperties.IsInDesignMode附加屬性

.NET Framework 4.5其他版本此主題尚未評級-評價此主題獲取或設置DependencyObject是否在設計器的上下文中運行。

命名空間:System.ComponentModel

程序集:PresentationFramework(在PresentationFramework.dll中)XAML的XMLNS:未映射到xmlns。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM