I want my form to display 1,2,3,4,5
but all it does is replace the text again and again.
for (int i = 1; i <= 5; i++)
{
richTextBox1.Text = Convert.ToString(i);
}
I know it's because of the .Text that it always overrides itself. But how can i leave them in the form so it will display:
1
2
3
4
5
The problem is that in your loop, you're completely replacing the text with each iteration. So the text is left with whatever the last value of i was.
Try putting adding to the current text (with +=) and putting a new line (Environment.NewLine or "\n") between each number:
for (int i = 1; i <= 5; i++)
{
richTextBox1.Text += Environment.NewLine + Convert.ToString(i);
}
Or alternatively, a little Linq can make your life a lot easier:
richTextBox1.Text = string.Join(Environment.NewLine, Enumerable.Range(1, 5));
Try this:
for (int i = 1; i <= 5; i++)
{
richTextBox1.Text += Convert.ToString(i) + Environment.NewLine;
}
Edit:
Just noticed that you want to print one number per line. \n is the NewLine character and will give you a carriage return on the end of the line.
Environment.NewLine is also a good choice, because it will give you the newline character based on the environment the app is running in.
append text, don't just assign it.
richTextBox1.Text += Convert.ToString(i);
this is equivelant of
richTextBox1.Text = richTextBox1.Text + Convert.ToString(i);
richTextBox1.AppendText(i.ToString()+Environment.NewLine);
This will also do:
for (int i = 1; i <= 5; i++)
{
richTextBox1.AppendText(i + Environment.NewLine);
}
Related
for (int i = 0; i < CheckBoxList3.Items.Count + 1; i++)
{
if (CheckBoxList3.Items[i].Selected || CheckBoxList4.Items[i].Selected || CheckBoxList5.Items[i].Selected)
{
str1 += CheckBoxList3.Items[i].Text.ToString() + "," + CheckBoxList4.Items[i].Text.ToString() +"," + CheckBoxList5.Items[i].Text.ToString() + ",";
I receive the error call "Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index". How to solve this issue?
What I want to do was collect the data from checkedbox in multiple check-box-list and combine together and store it into database.
Any suggestion or help would be great. Thanks
UPDATE : This is one of my check box list. The error point to my second line of the for loop.
<asp:CheckBoxList ID="CheckBoxList3" runat="server" RepeatDirection="Horizontal" Width="900px">
<asp:ListItem>Chicken</asp:ListItem>
<asp:ListItem>Tomato</asp:ListItem>
<asp:ListItem>Garlic</asp:ListItem>
</asp:CheckBoxList>
Wrong line 1: for (int i = 0; i < CheckBoxList3.Items.Count + 1; i++
Wrong line 2: CheckBoxList3.Items[i].Selected || CheckBoxList4.Items[i].Selected || CheckBoxList5.Items[i].Selected
Wrong line 3: str1 += CheckBoxList3.Items[i].Text.ToString() + "," + CheckBoxList4.Items[i].Text.ToString() +"," + CheckBoxList5.Items[i].Text.ToString() + ",";
You need to change your for loop condition from CheckBoxList3.Items.Count + 1 to CheckBoxList3.Items.Count
Also your condition checking only CheckBoxList3.Items.Count but you are using CheckBoxList4.Items.Count and CheckBoxList5.Items.Count
It seems CheckBoxList4 and CheckBoxList5 don't have enough item like CheckBoxList3.
Please Check your all individual CheckboxList objects to use same indexer.
Hope this helps.
//EDIT
Best practice:
string result = CombineCheckboxLists(checkBoxList1, checkBoxList2, checkboxlist3);
private string CombineCheckboxLists(params CheckBoxList[] list)
{
StringBuilder builder = new StringBuilder();
string result = string.Empty;
if (list?.Length > 0)
{
int minItemsCount = list.Min(l => l.Items.Count);
if (minItemsCount > 0)
{
for (int i = 0; i < minItemsCount; i++)
{
builder.Append(string.Join(",", list
.Where(l => l.Items[i].Selected)
.Select(l=> l.Items[i].Text)));
//if you want to merge all iteration via ",", please use following lines instead of above -- [marked as **]
// ** //builder.Append($"{string.Join(",", list.Select(l => l.Items[i].Value))},");
}
}
}
result = builder.ToString();
// ** // result = result.TrimEnd(',');
return result;
}
Just change your for loop like below:
for (int i = 0; i < CheckBoxList3.Items.Count; i++)
if (CheckBoxList3.Items[i].Selected)
str1 += CheckBoxList3.Items[i].Text.ToString() + ",";
for (int i = 0; i < CheckBoxList4.Items.Count; i++)
if (CheckBoxList4.Items[i].Selected)
str1 += CheckBoxList4.Items[i].Text.ToString() + ",";
for (int i = 0; i < CheckBoxList5.Items.Count; i++)
if (CheckBoxList5.Items[i].Selected)
str1 += CheckBoxList5.Items[i].Text.ToString() + ",";
UPDATE
#Caner LENGER has a good idea. But as I mentioned in the comment of his answer it's partially true, because list.Min returns minimum value of a list that in your case it's not gonna work. Why?
Imagine you have 3 CheckBoxLists that each one has 3 items in it except one of them that has 4. Using list.Min you'll get 3, No matter what's inside the 4th value of CheckBoxList.
So, I changed his code and here is the tested result:
public static string CombineCheckboxLists(params CheckBoxList[] list)
{
StringBuilder sb = new StringBuilder();
foreach (CheckBoxList checkBoxList in list)
{
int counter = checkBoxList.Items.Count;
for (int i = 0; i < counter; i++)
sb.Append(checkBoxList.Items[i].Selected ? checkBoxList.Items[i].Text + "," : "");
}
return sb.ToString();
}
Trying to get a simple 2 dimensional array to display to a text box. Output should look like this:
Student Class House
Jack Math Oxford
Bender Chem Trent
All previous attempts have failed and I am not sure how to output the code.
String[,] text = {
{ "Student", "Class", "House" },
{ "Jack", "Math", "Oxford" },
{ "Bender", "Chem", "Trent" } };
//string textString;
for (int i = 0; i < text.GetUpperBound(0); i++)
{
string first = text[i, 0];
string middle = text[i, 1];
string last = text[i, 2];
TextBox1.Text = first;
TextBox1.Text = middle;
TextBox1.Text = last;
}
You need to concatenate the text onto your strings and pass the strings to the texbox only once, after you're all done. You'll want to add in line breaks to have the data go over several lines as well.
Something like this (untested):
String[,] text = {
{ "Student", "Class", "House" },
{ "Jack", "Math", "Oxford" },
{ "Bender", "Chem", "Trent" } };
string output = '';
//string textString;
for (int i = 0; i < text.GetUpperBound(0); i++)
{
output += text[i, 0] + text[i, 1] + text[i, 2] + Environment.NewLine;
}
TextBox1.Text = output;
At the moment you're just adding things to the textbox and then overwriting them on the next loop.
so i think you problem that you are using textbox try textarea.
the reason is that textbox only take only line but textare you can have multiple lines and you are overwriting the text of the textbox every time by doing this TextBox1.Text = first;
TextBox1.Text = middle;
TextBox1.Text = last;
so try this better
TextBox1.Text += first + " " + middle+" " + last;
If both dimensions are dynamic, you can use a second loop nested it in the one you have. Each loop will be going through one dimension:
for (int i = 0; i < text.GetLength(0); i++)
{
for (int j = 0; j < text.GetLength(1); j++)
{
TextBox1Text += text[i, j] + "\t";
}
TextBox1.Text += "\r\n";
}
Note: I used tab \t to separate the columns and new line \r\n to separate the rows. However, this format will not be visible in a textbox, you'll need to use a textarea. Here is a demo.
So am working on a text mining project and currently trying to implement info gain. I have a data in which each line depict a document. so a new line character splits different documents.
i have to generate a matrix in which columns are all the distinct words in all documents and rows are different document. each cell in this table is either 1(true) or 0(false) for if the word is present or not in that document.
there are 987 documents, total words are 22860 and total distinct words are 3680. so 3680 words are compared with 22860. this is running slow but am fine with it. The loop that is taking more time is when i traverse through the objects of list of words to generate matrix. see below
Note: i have removed all repeated words in a document already.
class word_list
{
public string word;
public List<bool> doc= new List<bool>();
};//class ends
private void button2_Click(object sender, EventArgs e)
{
//Convert the string into an array of words
string[] w1 = richTextBox1.Text.Trim().Split('\n',' ').Select(x => x.Trim().ToLower()).Distinct().ToArray(); //all distinct words
string[] rich_doc = richTextBox1.Text.Trim().Split('\n'); //all documents array
List<word_list> words = new List<word_list>();
richTextBox2.Text+=("no. of distict words: " + w1.Length + ", no. of docs " + rich_doc.Length);
for (int i = 0; i < w1.Length; i++)
{
word_list temp = new word_list();
temp.word = w1[i]; //temp has the current distict word as class object
for(int j=0;j<rich_doc.Length;j++)//traverse all doc array
{
temp.doc.Add(false);
List<string> doc_word = Regex.Split(rich_doc[j], #"\b").Distinct(StringComparer.CurrentCultureIgnoreCase).ToList();
//richTextBox2.Text += ("\n no. of words in this doc: " + doc_word.Count);
//richTextBox2.SelectionStart = richTextBox1.Text.Length;
//richTextBox2.Focus();
int doc_count = doc_word.Count; // number of docs
for (int k = 0; k < doc_count; k++)//All words in a doc are compared
{
if(doc_word[k].ToLower() == w1[i].ToLower())
{
temp.doc[temp.doc.Count-1]=true;
break;
}
}
}
if ((words.Count - 1)>=0)
richTextBox2.Text += ("\n word(" + words.Count + "/" + w1.Length + "): " + words[words.Count - 1].word);
richTextBox2.SelectionStart = richTextBox1.Text.Length;
richTextBox2.Focus();
words.Add(temp);
}
//generate matrix
int t = rich_doc.Length; //no. of docs
int word_count = words.Count;
richTextBox1.Text = "Doc";
foreach (word_list w in words)
{
richTextBox1.Text += "\t" + w.word;
}
richTextBox1.Text += "\n";
//This loop is slow
for (int i = 0; i < t; i++) //traverse through number of docs
{
richTextBox1.Text += i + 1;
for (int h = 0; h < word_count; h++)//traverse through each distinct word in the list
{
if (words[h].doc[i])
richTextBox1.Text += "\t1";
else
richTextBox1.Text += "\t0";
}
richTextBox1.Text += "\n";
}
}//end of button 2
ta.speot.is is correct. Strings are supposed to be built with StringBuilder, using Append for instance, and only after the loop you assign the string to richTextBox1.Text. The code would look like this:
//generate matrix
StringBuilder sb = new StringBuilder();
int t = rich_doc.Length; //no. of docs
int word_count = words.Count;
richTextBox1.Text = "Doc";
foreach (word_list w in words)
{
sb.Append("\t");
sb.Append(w.word);
}
sb.AppendLine();
//This loop is not slow anymore :)
for (int i = 0; i < t; i++) //traverse through number of docs
{
sb.Append(i + 1);
for (int h = 0; h < word_count; h++)//traverse through each distinct word in the list
{
if (words[h].doc[i])
sb.Append("\t1");
else
sb.Append("\t0");
}
sb.AppendLine();
}
richTextBox1.Text = sb.ToString();
EDIT: There are valuable comments below. Changing RichEditBox.Text property is the most expensive operation here.
How to get richtextbox lines without displaying the content on it, I have a code like this under the button2
for (int i = 0; i < split.Length; i++)
richTextBox2.Text* += split[i] + "\n";
MessageBox.Show("Tamam!");`
but it takes too much time to display the content on Richtext, If I did not use this code above, there have another code under the button3 which is related with the code above
foreach (string line in *richTextBox2.Lines*)
how should I do to solve this problem?
Not knowing what you exactly want to achieve but if updating of the control takes a lot of time you might try before to start the loop in buton2 to stop rendering the control. Don't forget to enable it again.
Like so:
richtextBox2.SuspendLayout();
for (int i = 0; i < split.Length; i++)
{
richTextBox2.Text* += split[i] + "\n";
}
MessageBox.Show("Tamam!");
richtexbox2.ResumeLayout();
http://msdn.microsoft.com/en-us/library/system.windows.forms.control.suspendlayout.aspx
Or buildup your string with a stringbuilder first and the assign:
var builder = new StringBuilder();
for (int i = 0; i < split.Length; i++)
{
builder.Append(split[i]);
builder.Append('\n');
}
richTextBox2.Text = builder.ToString();
http://msdn.microsoft.com/en-us/library/y9sxk6fy.aspx
I have a textbox with multiline enabled, and want to add a string at the beginning and end of
each line, so every line would be changed to
a + line + b
Now I know it has to do with a foreach loop, but don't know how to write it out.
Well, the Lines property is probably the one you want. Three options:
string[] lines = textBox.Lines;
for (int i = 0; i < lines.Length; i++)
{
lines[i] = a + lines[i] + b;
}
textBox.Lines = lines;
Or:
textBox.Lines = Array.ConvertAll(textBox.Lines, line => a + line + b);
Or:
textBox.Lines = textBox.Lines
.Select(line => a + line + b)
.ToArray();
You can use a replace on the entire text:
text = a + text.Replace(Environment.NewLine, b + Environment.NewLine + a) + b;
Since you mentioned foreach, here's another way.
var newLines = new List<string>(textBox1.Lines.Length);
foreach (string line in textBox1.Lines)
newLines.Add(a + line + b);
textBox1.Lines = newLines.ToArray();
Here is what i use to add the characters a and b to the beginning and the end to a string that contains a bunch of lines :
public string Script;
string[] lines = Script.Split(new[] { '\r', '\n' });
for (int i = 0; i < lines.Length; i++)
{
lines[i] = a + lines[i] + b;
if (!lines[i].Equals("\"\"+"))
{
Console.WriteLine(lines[i]);
Result += lines[i]+"\n";
}
}