使用C#在富文本框中显示数据 [英] Displaying Data in Rich Textbox Using C#
本文介绍了使用C#在富文本框中显示数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在Windows窗体应用程序中有一个富文本框。
我想显示来自for循环的数据。我的代码是:
I have a rich textbox in a Windows Forms Application.
I want to display data from a for loop. My Code is:
ArrayList arr = new ArrayList();
for (int i = frm; i <= to; i++)
{
//I have stored the data as barcode by concatinating and adding it to arr
barcode = prefix + i + suffix;
arr.Add(barcode);
//MessageBox.Show(barcode);
}
richTextBox1.Text = arr.ToString();
foreach (string s in arr)
{
richTextBox1.Text = s;
//WHat should i do next to display the coming output from my foreach loop to that richtextbox?
//Currently it shows the last element of my output. How to display all the list elements?
推荐答案
试试这段代码...
Try this code...
private void Form1_Load(object sender, EventArgs e)
{
string barcode = "";
string prefix = "prefix";
string suffix = "suffix";
int frm = 0;
int to = 10;
ArrayList arr = new ArrayList();
for (int i = frm; i <= to; i++)
{
barcode = prefix + i + suffix;
arr.Add(barcode);
}
foreach (string s in arr)
{ richTextBox1.Text += s + Environment.NewLine;
}
}
首先关闭arr.ToString赢了; t帮助它只会给你类型的名称,而不是任何内容。即System.Collections.ArrayList
其次,请不要再使用ArrayList了 - 它近十年前被取代了,更安全,更灵活的通用诸如List<>之类的集合
第三,你的问题只是你每次都设置了富文本框文本,扔掉了之前的任何文本。
试试这个:
First off arr.ToString won;t help it will just give you the name of the type, rather than any of the content. Namely "System.Collections.ArrayList"
Second, please don't use ArrayList any more - it was superceded nearly ten years ago with teh much safer and more flexible generic collection such as List<>
Thirdly, your problem is simply that you are setting the rich text box text each time, throwing away any previous text.
Try this:
List<string> list = new List<string>();
for (int i = frm; i <= to; i++)
{
//I have stored the data as barcode by concatinating and adding it to arr
barcode = prefix + i + suffix;
list.Add(barcode);
//MessageBox.Show(barcode);
}
StringBuilder sb = new StringBuilder();
foreach (string s in list)
{
sb.Append(s);
}
richTextBox1.Text = sb.ToString;
或者,如果您不再需要数据:
Or if you don't need the data again:
richTextBox1.Clear();
for (int i = frm; i <= to; i++)
{
richTextBox1.AppendText(string.Format("{0}{1}{2}", prefix, i, suffix));
}
替换所有代码......
Replaces all of your code...
这篇关于使用C#在富文本框中显示数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文