2012-09-30 228 views
0

对于C#我还是一个新手,所以请耐心等待。从Form2中的文本框写入Form1中的Datagridview

我有Form1与DataGridViewButton。此按钮打开Form2

Form2包含TextBoxButton,其关闭Form2

我需要将TextBox中的文本Form2写入Form1中DataGridView的第一个单元格中。在我正在开发的应用程序中,Form1中的DataGridView中已有其他数据。

我已经上传了Visual Studio 2010文件here

编辑:

请看看这个截图:

enter image description here

这里是我使用的代码:

public partial class Form2 : Form 
{ 
    public Form2() 
    { 
     InitializeComponent(); 
    } 

    private void button1_Click(object sender, EventArgs e) 
    { 
     Form1 form1 = new Form1(); 
     form1.dataGridView1.Rows[0].Cells[0].Value = textBox1.Text; 
     this.Close(); 
    } 
} 

我似乎实例化一个新的Form1,当我不想。

欣赏帮助。

+3

请请勿将代码发布到第三方服务。将相关部分的源代码直接放入您的问题中。 –

+2

你应该给你的表格命名。 – SLaks

+0

Ondrej Ttucny:我添加了代码。 – user1580591

回答

1

您不需要Form2来实例化(再次)主窗体(Form1)。

更合适的方法是打开包含文本框的辅助表单作为模式对话框窗口,并让开启者窗体(Form1)访问用户输入的文字Form2实例。

这里介绍如下所需的变革:

Form2变化:

1.-添加一个新的类成员来存储在文本框textBox1要引入的字符串。

public String textFromTextBox = null; 

2:将代码添加到您的OK按钮的CLIC事件处理程序,让你在新的类成员textFromTextBox在文本框中推出的值存储:

3.-最后,在同样的clic事件处理代码将DialogResult属性设置为DialogResult.OK

Form2代码应该是这样的:

public partial class Form2 : Form 
{ 
    [...] 

    // This class member will store the string value 
    // the user enters in the text-box 
    public String textFromTextBox = null; 

    [...] 

    // This is the event-handling code that you must place for 
    // the OK button. 
    private void button1_Click(object sender, EventArgs e) 
    { 
     this.textFromTextBox = this.textBox1.Text; 
     this.DialogResult = DialogResult.OK; 
    } 
} 

Form1改变

1.-在与标签 “输入文字” 您的按钮(即实际上是缺少在你的代码),在Click事件处理程序中将打开Form2所需的代码作为模式Dialog打开。

2.-通过恢复存储在Form2textFromTextBox成员中的值来相应地设置数据网格中的单元格值。

3.-最后处理你的Form2实例。

Form2 myFormWithATextBox = new Form2(); 

    if (myFormWithATextBox.ShowDialog(this) == DialogResult.OK) 
    { 
     this.dataGridView1.Rows[0].Cells[0].Value = myFormWithATextBox.textFromTextBox; 
    } 
    myFormWithATextBox.Dispose(); 

要考虑到你的主要形式是Form1Form2它只是一个辅助表单控件,它不应该在你的应用程序的流量多的控制,因此不承担实例化的主要形式的责任。

0

您可以从形式传递变量到另一个创建接受参数,如下另一承包商: -

1)去到Form1,然后创建另一个承包商:

public Form1(string myString) 
    { 
     InitializeComponent(); 

     if (myString != null) 
      dataGridView1.Rows[0].Cells[0].Value = myString; 
    } 

2)去窗口2和按钮下方写这样的代码:

private void button1_Click(object sender, EventArgs e) 
    { 
     Form1 frm1 = new Form1(textBox1.Text); 
     frm1.ShowDialog(); 
    } 

Here you are your application after modification

相关问题