如何通过单击form1上的按钮在form2 dinamicaly上添加文本框? [英] How to add text boxes on form2 dinamicaly by clicking the button on form1?

查看:59
本文介绍了如何通过单击form1上的按钮在form2 dinamicaly上添加文本框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经编写了一个代码,可以在同一页面上点击按钮添加文本框。并且代码运行得很好。现在我想在Form1上单击按钮时在其他表单上添加多个文本框,例如Form2。

下面是我为在同一页面上添加文本框而编写的代码。你能不能帮我在其他页面上添加文本框。



我尝试过:



公共部分类Form1:表格

{

static int j = 1;

public Form1()< br $>
{

initializeComponent();

}

private void button1_Click(object sender,EventArgs e)



{

TextBox tb = new TextBox();

tb.text =+ j;



点数p =新点数(20 + j,30 * j);

tb.Location = p

this .Controls.Add(tb);

j ++

}

}

解决方案

< blockquote>不要。

相反,在Form2上使用相同的代码在那里添加文本框并从Form1调用它:

 < span class =code-keyword> public   partial   class  Form1:Form 
{
...
private void button1_Click( object sender,EventArgs e)
{
Form2 f2 = new Form2();
f2.AddTextBoxes();
f2.Show();
}
}



  public   partial   class  Form2:Form 
{
...
public void AddTextBoxes( int count)
{
for int i = 1 ; i < = count; i ++)
{
TextBox tb = new TextBox();
tb.text = + i;
点p = 点( 20 + i, 30 * i);
tb.Location = p
Controls.Add(tb);
}
}
}

这样,Form2不需要知道Form1存在,并且Form1没有锁定到Form2的内部。


查看代码,我发现你没有保留对在运行时创建的文本框控件的引用。 button1_Click代码退出的那一刻没有变量'tb。



因此,如果您想要阅读其中一个创建的TextBox中的Text,那么您将拥有找到它,但是,你甚至没有给TextBox一个明确的标识'名称值:如果表格上有很多其他控件你会怎么找到它?



这几乎总是一个错误,因为你想要...在任何真正的应用程序中...在某些时候使用运行时创建的控件...在TextBoxes的情况下:读取他们的文本内容,设置他们的文本内容。并且,您可能希望将一些事件附加到那些运行时创建的控件上。



有多种方法可以跟踪TextBox;这是一个想法:



a。创建一个新的WinForm项目:'TestRunTimeControlCreation



b。在Form1上放两个按钮:'button1',button2



c。在项目中添加第二个表格:'Form2



d。用以下代码替换Form1的自动生成代码:

   #region地区:

< span class =code-keyword>使用系统;
使用 System.Collections.Generic;
使用 System.Drawing;
使用 System.Windows.Forms;

#endregion

namespace TestRunTimeControlCreation
public partial class Form1:表格
{
private const string TextBoxNamePrefix = tbx _;

private readonly 字典< string,TextBox> _dctForm1NameToTBox = new Dictionary< string,TextBox>();

private readonly 字典< string,TextBox> _dctForm2NameToTBox = new Dictionary< string,TextBox>();

private readonly Form2 _form2Instance;

public Form1()
{
InitializeComponent();
}

private void Form1_Load( object sender,EventArgs e)
{
_form2Instance = new Form2();
_form2Instance.Show();
}

private void button1_Click( object sender,EventArgs e)
{
AddTextBoxToForm( this 5 );
}

private void button2_Click( object sender,EventArgs e)
{
AddTextBoxToForm(_form2Instance, 5 );
}

public void AddTextBoxToForm(表单targetform, int nTextBox)
{
if (targetform == null || nTextBox < 1
{
throw new ArgumentException( < span class =code-string> AddTextBoxToForm中的错误
);
}

string namebase = string .Format( {0} {1},targetform.Name,TextBoxNamePrefix);

int tBxCnt;

for var x = 0 ; x < nTextBox; x ++)
{
var newTextBox = new TextBox();
newTextBox.Size = new 大小( 100 25 );

targetform.Controls.Add(newTextBox);

如果(targetform Form1)
{
tBxCnt = _dctForm1NameToTBox.Count;
newTextBox.Name = string .Format( {0} {1},namebase,tBxCnt);

_dctForm1NameToTBox.Add(newTextBox.Name,newTextBox);

// 在Form1上设置位置
newTextBox.Location = new 点( 30 ,tBxCnt * 40 + 60 < /跨度>);
}
else if (targetform Form2)
{
tBxCnt = _dctForm2NameToTBox.Count;
newTextBox.Name = string .Format( {0} {1},namebase,tBxCnt);

_dctForm2NameToTBox.Add(newTextBox.Name,newTextBox);

// 在此处设置Form2上的位置
newTextBox.Location = new 点( 30 ,tBxCnt * 40 + 30 < /跨度>);
}
其他
{
// < span class =code-comment>出了点问题!

throw new ArgumentException( string .Format( 无效的Form参数{ 0},targetform.Name));
}

newTextBox.Enter + = OnTextBoxEnter;
newTextBox.Leave + = OnTextBoxLeave;

// 在这里应用您自己的标签方案?
newTextBox .Text = newTextBox.Name;
}
}

私有 void OnTextBoxLeave( object sender,EventArgs eventArgs)
{
TextBox tBox = sender as TextBox;
Console.WriteLine( 离开TextBox:{0} TextBox:{1} text:{2} ,tBox.TopLevelControl.Name,tBox.Name,tBox.Text);
}

private void OnTextBoxEnter( object sender,EventArgs eventArgs)
{
TextBox tBox = sender as TextBox;
Console.WriteLine( 输入TextBox:{0} TextBox:{1} text:{2} ,tBox.TopLevelControl.Name,tBox.Name,tBox.Text);
}
}
}

将Form1上的两个按钮的EventHandlers连接到'button1和'button2 ClickHandlers。



运行项目。单击按钮,单击Form1上的几个TextBox,单击Form2上的几个TextBox。然后:检查已写入控制台的内容(在Visual Studio的输出窗口中)。



一旦创建了这种字典结构来映射'名称您已分配给运行时创建的TextBoxes的属性,您可以使用字符串'Name key:

 TextBox getATbx;访问任何TextBox。 

if (_ dctForm1NameToTBox.TryGetValue( Form1_Tbx_2 out getATbx))
{
// getATbx有一个文本框
}


I have write a code which add Text boxes on button click on same page . and the code works pretty well. now i want to add multiple text boxes on other form say Form2 when i click on button on Form1.
Below is the code that i have written for addition of text boxes on same page . could you please help me to add the text boxes on other page.

What I have tried:

public partial class Form1:Form
{
static int j=1;
public Form1()
{
initializeComponent();
}
private void button1_Click(object sender, EventArgs e)

{
TextBox tb = new TextBox();
tb.text = " " + j;

Point p = new Point(20 + j,30* j);
tb.Location = p
this.Controls.Add(tb);
j++
}
}

解决方案

Don't.
Instead, use the same code on Form2 to add the textboxes there and call that from Form1:

public partial class Form1:Form
    {
    ...
    private void button1_Click(object sender, EventArgs e)
        {
        Form2 f2 = new Form2();
        f2.AddTextBoxes();
        f2.Show();
        }
    }


public partial class Form2:Form
    {
    ...
    public void AddTextBoxes(int count)
        {
        for (int i = 1; i <= count; i++)
            {
            TextBox tb = new TextBox();
            tb.text = " " + i;
            Point p = new Point(20 + i,30 * i);
            tb.Location = p
            Controls.Add(tb);
            }
        }
    }

That way, Form2 doesn't need to know that Form1 exists, and Form1 isn't locked into the internals of Form2.


Looking at your code, I see you do not keep a reference to the Textbox Controls you create at run-time. The moment the button1_Click code exits there is no variable 'tb.

So, if you wnat to read the Text in one of these created TextBoxes, you are going to have to find it, but, you haven't even given the TextBoxes a distinct identifying 'Name value: how will you find it if the Form has lots of other Controls on it ?

This is almost always a mistake, because you are going to want to ... in any real application ... at some point use run-time created Controls ... in the case of TextBoxes: read their Text content, set their Text content. And, you will probably want to attach some events to those run-time created Controls.

There are a variety of ways you could keep track of the TextBoxes; here's one idea:

a. create a new WinForm project: 'TestRunTimeControlCreation

b. put two Buttons on Form1: 'button1, 'button2

c. add a second Form to the project: 'Form2

d. replace the auto-generated code for Form1 with this:

#region Region:

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;

#endregion

namespace TestRunTimeControlCreation
    public partial class Form1 : Form
    {
        private const string TextBoxNamePrefix = "tbx_";

        private readonly Dictionary<string, TextBox> _dctForm1NameToTBox = new Dictionary<string, TextBox>();

        private readonly Dictionary<string, TextBox> _dctForm2NameToTBox = new Dictionary<string, TextBox>();

        private readonly Form2 _form2Instance;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            _form2Instance = new Form2();
            _form2Instance.Show();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            AddTextBoxToForm(this, 5);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            AddTextBoxToForm(_form2Instance, 5);
        }

        public void AddTextBoxToForm(Form targetform, int nTextBox)
        {
            if (targetform == null || nTextBox < 1)
            {
                throw new ArgumentException("error in AddTextBoxToForm");
            }

            string namebase = string.Format("{0}{1}", targetform.Name, TextBoxNamePrefix);

            int tBxCnt;

            for (var x = 0; x < nTextBox; x++)
            {
                var newTextBox = new TextBox();
                newTextBox.Size = new Size(100,25);

                targetform.Controls.Add(newTextBox);

                if (targetform is Form1)
                {
                    tBxCnt = _dctForm1NameToTBox.Count;
                    newTextBox.Name = string.Format("{0}{1}", namebase, tBxCnt);

                    _dctForm1NameToTBox.Add(newTextBox.Name, newTextBox);
                    
                    // set location on Form1 here
                    newTextBox.Location = new Point(30, tBxCnt*40 + 60);
                }
                else if (targetform is Form2)
                {
                    tBxCnt = _dctForm2NameToTBox.Count;
                    newTextBox.Name = string.Format("{0}{1}", namebase, tBxCnt);

                    _dctForm2NameToTBox.Add(newTextBox.Name, newTextBox);

                    // set location on Form2 here
                    newTextBox.Location = new Point(30, tBxCnt*40 + 30);
                }
                else
                {
                    // something is wrong !
                    throw new ArgumentException(string.Format("invalid Form parameter{0}", targetform.Name));
                }

                newTextBox.Enter += OnTextBoxEnter;
                newTextBox.Leave += OnTextBoxLeave;

                // apply your own labeling scheme here ?
                newTextBox.Text = newTextBox.Name;
            }
        }

        private void OnTextBoxLeave(object sender, EventArgs eventArgs)
        {
            TextBox tBox = sender as TextBox;
            Console.WriteLine("Leave TextBox: {0} TextBox: {1} text: {2}", tBox.TopLevelControl.Name, tBox.Name, tBox.Text);
        }

        private void OnTextBoxEnter(object sender, EventArgs eventArgs)
        {
            TextBox tBox = sender as TextBox;
            Console.WriteLine("Enter TextBox: {0} TextBox: {1} text: {2}", tBox.TopLevelControl.Name, tBox.Name, tBox.Text);
        }
    }
}

Hook-up the EventHandlers for the two Buttons on Form1 to the 'button1 and 'button2 ClickHandlers.

Run the project. Click the Buttons, click in a few TextBoxes on Form1, click in a few TextBoxes on Form2. Then: examine what has been written to the Console (in the Visual Studio 'Output window).

Once you have created this kind of Dictionary structure to map the 'Name properties you have assigned to the run-time created TextBoxes, you can access any TextBox using the string 'Name key:

TextBox getATbx;

if(_dctForm1NameToTBox.TryGetValue("Form1_Tbx_2", out getATbx))
{
    // getATbx got a Textbox
}


这篇关于如何通过单击form1上的按钮在form2 dinamicaly上添加文本框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆