none
Form1中的控件为什么会消失? RRS feed

  • 问题

  • Public Class Form1
        '设计时在Form1中画了一个ComboBox,一个Button
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
            Form2.Show()
        End Sub
    End Class

    Public Class Form2
        Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            Dim a As New ComboBox
            a = Form1.ComboBox1
            Me.Controls.Add(a)
            a.Visible = True
            '此代码执行完毕后,Form1中的ComboBox1消失了
             '如何理解这种现象?
        End Sub
    End Class


    学无止境

    2013年7月7日 8:26

答案

  • 因为你的a指向的是Form1窗体所容纳的对象,因此窗体2引用窗体1的控件对象。但是设计者貌似不允许这样做(反射基类Control可以看到源码如下,注意黑色部分):

    public virtual void Add(Control value)
                {
                 ……………………
                    if (value.parent != null)
                    {
                        value.parent.Controls.Remove(value);
                    }

                 ……………………
               }


    If you think one reply solves your problem, please mark it as An Answer, if you think someone's reply helps you, please mark it as a Proposed Answer

    Help by clicking:
    Click here to donate your rice to the poor
    Click to Donate
    Click to feed Dogs & Cats


    Found any spamming-senders? Please report at: Spam Report

    2013年7月7日 8:35
    版主