I'm trying to get the contents of a StringBuilder to display in a WinForms textbox, but the window never appears when I try to compile the program. This is my first venture into WinForms and C# and I've only used the language for about a week and a half now, so this is probably a simple fix that I'm just not seeing.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
StringBuilder builder = new StringBuilder();
Random rand = new Random();
int[] builderList = new int[10000];
for (int i = 0; i < 10000; i++)
{
builderList[i] = rand.Next(1, 20000);
builder.Append(builderList[i].ToString() + " ");
}
// This is the line that seems to be the problem...
textBox1.Text = builder.ToString();
}
}
When I try to run the program and insert a breakpoint on that last line of code, I can see that the program seems to just hit that line continuously. Oddly enough, if I change that line to this:
textBox1.Text = "Hey, lol";
my program will run. I checked the debugger in Visual Studio and saw that the contents of 'builderList' are updated to random numbers and 'builder' looks like it's correctly storing the values in 'builderList' as a string like I want, so I'm kind of confused about what's going on here. I'd appreciate any help I can get on this one as it seems like it should be a relatively easy fix but I've been stumped on it so far and I haven't really found anything helpful in the MSDN documentation.
Thanks so much!
Change your TextBox1 to be a MultiLine TextBox.Select "Allow multiLine"
The real reason for this is about the pixel width, check my post and #TaW's answer here: The maximum number of characters a TextBox can display
Related
I am very new to programming and I am working on a project for school in Visual Studio but I am kinda stuck. I have multiple forms in my solution. One of my forms is an invoice and I am trying to create an invoice number when the checkout button on the previous form is clicked. I have the following code in the textBox field that I want to display my number but the number is not showing in the textBox. Please help!!
private void txtBoxInvoiceNo_TextChanged(object sender, EventArgs e)
{
Random rndNo = new Random();
int invoiceNo = rndNo.Next(1, 500);
txtInvoiceNo.Text = invoiceNo.ToString();
}
Probably need to see a bit more code here, but from what you have shown it suggests you are generating the invoice number on the textChanged event of txtBoxInvoiceNo. This event will fire when the text changes within that box. Not on creation of the form.
My suggestion would be to call a function on construction of your form. The code you have written should work, it just needs to be called in the right place.
I'm assuming you're writing winforms but something like:
public MyForm()
{
InitializeComponent();
GenerateInvoiceNumber();
}
private void GenerateInvoiceNumber()
{
Random rndNo = new Random();
int invoiceNo = rndNo.Next(1, 500);
txtInvoiceNo.Text = invoiceNo.ToString();
}
You can refactor this later into a static or extension method so it can be used by multiple forms, but the call should be made in the constructor, not in a text box changed event.
If you want to utilize something on multiple forms you better Add a Class and write a method which will return integer. Refer below sample
Public class GenerateNumber
{
public static int GetRandomNo()
{
Random rndNo = new Random();
int invoiceNo = rndNo.Next(1, 500);
return invoiceNo;
}
}
Then you can make object of class and call this function on the required form. Refer Below code
GenerateNumber randomNo = new GenerateNo();
txtInvoiceNo.Text = randomNo.GetRandomNo().ToString()
im trying to get a textbox to autoscroll a line down every X seconds.
i have found the AutoScrollOffset and ScrollToCaret functions, but these functions do not give the desired result.
I think my solution would be to do the autoscroll function in a backgroundworkerthread, that does a scroll down by 1 line every x seconds. But i have no idea how to, and info from the net isnt verry usefull either.
I hope someone can help me, thnx in advance!
(im using .net 4.5)
Borrowing heavily from this answer, and combining it with a Timer, you could do something like this:
private int lineNumber = 1;
private void timer1_Tick(object sender, EventArgs e)
{
nfobox.HideSelection = false;
nfobox.SelectionStart = nfobox.GetFirstCharIndexFromLine(lineNumber - 1);
nfobox.SelectionLength = nfobox.Lines[lineNumber - 1].Length;
nfobox.ScrollToCaret();
lineNumber++;
// include some code to detect the last line, or you'll get an exception
}
This will only work if your lines are separated by a line feed.
If it's one long line that wraps, then the whole thing will be selected on the first "tick" and then it's done.
"Grant Winney" is rigth. you can't directly modify the Uİ from a background thread.
But You use the way below.
int lineCounter = 0;
int nextLineLength = 0;
private void timer1_Tick(object sender, EventArgs e)
{
textBox1.SelectionStart = nextLineLength;
textBox1.SelectionLength = 0;
textBox1.ScrollToCaret();
nextLineLength += textBox1.Lines[lineCounter++].Length + "\r\n".Length; //"\r\n" is next line parameters
}
This question already has answers here:
Multithreading in C# with Win.Forms control
(2 answers)
Closed 9 years ago.
I'm beginner in C#. And I don't understand why next two examples are giving different results. I'm using microsoft example in msdn. In first example it displays one number in the textbox. In second example it displays all numbers from 0 to 1000 for each thread.
First example:
delegate void SetTextCallback(object text);
private void WriteString(object text)
{
if (this.textBox1.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(WriteString);
this.BeginInvoke(d, new object[] { text });
}
else
{
for (int i = 0; i <= 1000; i++)
{
textBox1.Text = text.ToString();
}
}
}
Second example:
private void MyApp_Load(object sender, EventArgs e)
{
System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;
}
private void WriteString(object text)
{
for (int i = 0; i <= 1000; i++)
{
textBox1.Text = text.ToString();
}
}
And method which calls these examples
private void button1_Click(object sender, EventArgs e)
{
Thread th_1 = new Thread(WriteString);
Thread th_2 = new Thread(WriteString);
Thread th_3 = new Thread(WriteString);
Thread th_4 = new Thread(WriteString);
th_1.Priority = ThreadPriority.Highest;
th_2.Priority = ThreadPriority.BelowNormal;
th_3.Priority = ThreadPriority.Normal;
th_4.Priority = ThreadPriority.Lowest;
th_1.Start("1");
th_2.Start("2");
th_3.Start("3");
th_4.Start("4");
th_1.Join();
th_2.Join();
th_3.Join();
th_4.Join();
}
Well I analyzed in my VS. I am also new to C#. But what I could infer is the following:
Program 1:
Begin Invoke is aynschronous way of calling a method. Thus it shows only one result at the end. If you have slowly did F11 in VS and observe, not really everytime you get the result 4. But sometime you get 3 too when you do F11 and go step by step at certain places(I mean delaying), due to multi threading. You should remember that, multi threading always never behave in same manner all the time, which means suppose if an application or module in multithreading gives you one result at a time, two times, and 10 times, you cannot be sure that its the correct or optimized code. Because at client environment, due to its own behavior, it can lead to different results which may potentially be unnoticed while debugging or it wont even happen. I read it in a nice blog.
Program 2:
Since its multithreading, I could see the behavior of different threads getting invoked at different time, and as it does the job, I see the textboxes are getting updated quickly in fraction of seconds thats not possible for an human eye to notice, but final result, a single number is displayed. Also you do check for cross thread calls )When you do step into every line of code using F11, you will find this behavior and understand well ) and you order not to catch it. This makes the threads to work together in second case.
This is my inference, but I can say, pretty corny! I don't claim this with confidence, but just my observation :)
Let some great folks chime in with their views to help us :)
Cheers
I am creating a website and wish to make a 'flashcard' page which shows interesting facts about the topic the site is based on (music).
I have created an arraylist and added some 'facts' to it as a string value.
I have a textbox on my page and I have a button and I want to show a different fact each time the button is clicked to the textbox.
What would be the best way to go about it?
Sorry I am a newbie here and am just getting to grips with ASP.NET and VS.
EDIT
Thanks, I have now changed it to list. Now I have stored multiple string values to that list and have set a string field called 'abc' (like so);
public partial class _Default : System.Web.UI.Page
{
private String abc;
public void do9()
{
List<String> list = new List<String>();
list.Add("aaa");
list.Add("bbb");
list.Add("ccc");
list.Add("ddd");
list.Add("eee");
foreach (String prime in list) // Loop through List with foreach
{
abc = prime;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
do9();
TextBox1.Text = abc;
}
}
Now how can I return a different list value upon the buttonclicked event? Currently it only returns 'eee'. Say I want it to return "aaa" etc instead when the button is clicked each time.
Thanks again!
Arraylist fell out of style with the generics that we got back in .NET 2.0. You should consider using a List<string> instead. I also suggest a shuffling algorithm like the Fisher-Yates shuffle.
I probably wouldn't do this server side at all but more likely in JavaScript. Here's Fisher-Yates shuffle in JavaScript.
EDIT
Here's one way to get a random element from a List.
private static List<string> QuoteArray = new List<string>
{
"All generalizations are false, including this one.",
"Be careful about reading health books. You may die of a misprint.",
"If you tell the truth, you don't have to remember anything.",
"It usually takes me more than three weeks to prepare a good impromptu speech",
"Water, taken in moderation, cannot hurt anybody.",
"When I was younger I could remember anything, whether it happened or not."
};
private static int LastQuoteIndex;
and in som class somewhere:
int i = 0;
var rnd = new Random();
do
{
i = rnd.Next(QuoteArray.Count);
}
while (i == LastQuoteIndex);
LastQuoteIndex = i;
TextBox1.Text = QuoteArray[i];
Im designing a game on visual C# the game must contain two text boxes and two bottons and a lable
in the first text bos I should enter the range of numbers the program should randomly generate. ---- and its activated by the botton.
the second text box is the place where i enter the guesses ,---- also there is a botton to read the number.
I will have a limit of ten guesses , each is assgined a color.
for example the game will start with the green and if my guess was wronge the color wil change to a darker color ( dark green ,darker ..... red etc) and if I guessed the right answer the screen will get back to the green with a lable that say you won !! or if I finished my guesse it show me Game Over !!
Now Im not that xpert in Visual C# so I find it hard where to write the code ... and how to activate actions as the color changing thing
BUT i understand that i need to use the random function and know how to set the range as you will see in the code below but Now Im stuck I don't know how to continue,,, Some one please guide me and help me.
private void button1_Click(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
int range;
range = int.Parse(textBox1.Text);
System.Random RandNum = new System.Random();
int Magicnumber = RandNum.Next(0, range);
int numberofguesses = 0;
}
private void button2_Click(object sender, EventArgs e)
{
int usersguess ;
usersguess = int.Parse(textBox2.Text);
if (usersguess == Magicnumber) ;
{
// I dont know what to write here
}
{
if (usersguess != Magicnumber);
{
// I dont know what to write here
}
}
}
}
}
I know this stupid but Im not pro and I would like to learn from you guys
and I belive this is the right place to ask ....
thanx in advance
(This started as a comment, but nobody mentioned it, and I got carried away...)
Please note that adding a semicolon after the if is a mistake (this is probably why else didn't work for you, and you've made this strange if-if anti pattern).
This is the proper way to write an if statement (else is optional, by the way):
if(key == 'Q')
{
LaunchMissiles();
}
else
{
GivePeaceAChance();
}
Now, what you've got there is quite different:
if(key == 'Q');
{
LaunchMissiles();
}
See that semicolon after the if? That means that if(key=='Q'); and LaunchMissiles(); are two different statements, rather then a condition. This is the same as:
if(key == 'Q') DoNothing();
LaunchMissiles();
Despite it's appearance, the curly braces won't help you here - you can group a bunch of statements in curly braces, but it has no effect on flow control (unless immediately after an if, or loop, of course).
your if statement needs a tidy up for a start:
if (usersguess == Magicnumber)
{
// I dont know what to write here
}
else
{
// I dont know what to write here
}
Hmmm this seems like a homework type question but anyway (Since you did not mention whether this is a winforms or asp.net app i am going to assume winforms) .
For starters you need to move the declaration of
int Magicnumber = RandNum.Next(0, range);
and make it a member variable so that it can be accessed by all the functions in your form.
Secondly in your button click you can set the back color of a button to show the colors changing or you can use images , i would go with the button since you can dynamically change its color by keeping a variable that store the hex value of a color and incrementing it on every failure e.g.
Color myColor = Color.FromArgb(100,123,23,myvar);
btnColor.BackColor = myColor;
By incrementing/decrementing myColor in the example above the backColor of the button will change on each failure. If the user gets the answer right then you can set the backColor to a default color of your choice.
First of all, here is the better way to write your 'if' construction:
if (int.Parse(textBox2.Text) == Magicnumber)
{
...
}
else
{
...
}
If you want to count the number of user attempts to guess the number, you should store it in a variable. And this variable should be reset to zero any time you start new game.
private int count = 0;
private void button2_Click(object sender, EventArgs e)
{
...
if (int.Parse(textBox2.Text) == Magicnumber)
{
// User wins
...
}
else
{
// Wrong answer
count++;
...
}
}
Then, if you want to change the background color of some WinForms control, use BackColor property (its value should depend of count). This example changes background color of TextEdit instance:
textEdit1.BackColor = Color.DarkGreen;
The Color here is System.Drawing.color class that may represent any color and have a lot of named values (http://msdn.microsoft.com/en-us/library/system.drawing.color.aspx, http://msdn.microsoft.com/en-us/library/aa358802%28VS.85%29.aspx). I strictly recomed you to begin with reading some good book on C# before trying to solve any programming tasks.