将信息从文件加载到窗口中

时间:2012-10-17 17:11:12

标签: c#

我有以下表格。第一个按钮打开一个文本文件,并在表单的富文本框中显示该文件。第二个按钮打开另一个窗口。我想要的是,该窗口预先填充了该文本文件中的数据......

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace HomeInventory2
{
    public partial class Form2 : Form
    {
        OpenFileDialog openFileDialog1 = new OpenFileDialog();
        public Form2()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, System.EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                richTextBox1.LoadFile(openFileDialog1.FileName, RichTextBoxStreamType.RichText);
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            Application.Run(new Form1());
        }
    }
}

需要填充的表单

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using HomeInventory2.Domain;
using HomeInventory2.Business;

namespace HomeInventory2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void submitButton_Click(object sender, EventArgs e)
        {
            CreateInventory create = new CreateInventory();
            create.ItemAmount = textBoxAmount.Text;
            create.ItemCategory = textBoxCategories.Text;
            create.ItemProperties = textBoxValue.Text;
            create.ItemValue = textBoxValue.Text;

            InventoryMngr invtryMngr = new InventoryMngr();
            invtryMngr.Create(create);

        }
    }
}

1 个答案:

答案 0 :(得分:2)

创建一个带有string重载的新构造函数。当您打开新的Form时,请传入文本日期并填写文本框。

//in the new form that opens up
public Form1(string prepopulated)
{
    InitializeComponent();
    myRichTextbox.Text = prepopulated;
}

并从您的点击事件中调用它:

//in the first form
private void button2_Click(object sender, EventArgs e)
{
    Application.Run(new Form1(richTextBox1.Text));
}

如果您的内容比简单的文本文件更复杂,您可以使用RichTextBox.Document代替并传递该内容而不是字符串。将过载更改为

Form1(FlowDocument prepopulated)

并像这样称呼它

Application.Run(new Form1(richTextBox1.Document));