English 中文(简体)
C#在板板上呼唤的方法?
原标题:c# calling methods on panel?

我创造了一些新方法:

void newMethod(int x, int y)
{
    Button B = new Button();
    B.Size = new Size(100, 30);
    B.Location = new Point(x, y);
    B.Text = "Text";
    Controls.Add(B);
}

现在我用其他方法 创造了一个新的面板:

void Something()
{
    Panel P = new Panel();
    P.Size = new Size(300, 300);
    P.Location = new Point(0, 0);
    P.BackColor = new Color(Blue);
    Controls.Add(P);
}

我如何将我第一个创建按钮的方法 添加到第二个方法的面板上?

最佳回答

添加父控件为参数 :

private void AddButton(int x, int y, Control parent)
{
    Button button = new Button
        {
            Size = new Size(100, 30),
            Location = new Point(x, y),
            Text = "Text"
        };

    parent.Controls.Add(button);
}

然后:

void Something()
{
    Panel P = new Panel();
    P.Size = new Size(300, 300);
    P.Location = new Point(0, 0);
    P.BackColor = new Color(Blue);

    this.AddButton(100, 100, P);
}
问题回答

编辑您的第一种方法

void newMethod(int x, int y, Panel p)
{
    Button B = new Button();
    B.Size = new Size(100, 30);
    B.Location = new Point(x, y);
    B.Text = "Text";
    p.Controls.Add(B);
}

大声声明,这是在教室里,不是在新方法里。

Panel P = new Panel();

然后写下这个代码

this.P.controls.Add(B);

< 坚固 > 内含 < / 坚固 >

Controls.Add(B);




相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签