I us开发者_开发百科e the same code to fill a control in my WinForms over and over again, so I figured: Hey, you should make it a method instead of copy-pasting it!
So, I created this in my Main
class
Main
internal static void FillWithStuff(RichTextBox box)
{
Data data = GetSomeData("doesn't matter");
foreach (Row row in data)
{
box.Text += row.ToString() + "\r\n";
}
}
WinForm
internal RichTextBox textBox = new RichTextBox();
// Some code
Main.FillWithStuff(textBox);
So, the method executes without exceptions or warnings, but the data is not filled in the box. I checked if the data was loaded and it is, so the problem has to be somewhere else.
How should I implement this correctly?
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private List<string> GetStuff()
{
List<string> stuff = new List<string>();
stuff.Add("foo");
stuff.Add("bar");
stuff.Add("baz");
return stuff;
}
private void FillWithStuff(TextBoxBase textBox)
{
List<string> stuff = GetStuff();
foreach (string s in stuff)
{
textBox.Text += s + "\r\n";
}
}
private void button1_Click(object sender, EventArgs e)
{
FillWithStuff(richTextBox1);
}
}
}
That works as you would expect. Comparing it with what you have makes me think you have a problem somewhere else. Are you sure row.ToString()
is returning a non-empty string?
Did you Call Main.FillWithStuff(...) after something like Application.Run(form) or form.ShowDialog()? In that case, Main.FillWithStuff(..) will not execute unless you close the form, try to move your method call before it
Can you paste in the entire code for the Winform?
From what I can tell it's a form-level variable as it's marked internal.
I tested this using a form that was already on the form as well as one that's dynamically created and both times it filled the RichTextBox with the text as expected.
Try putting a break point in your foreach loop and ensure it's returning data.
精彩评论