My Professor gave us this question
Write a method called Drawline that accepts as input an integer n and generates a line of output in lstOutput with n hyphens. That is, if n = 5 we have a line of ‘-----‘ displayed in the list box.
Basically he wants me to type a number in a text box and when i click the button it should display that many hyphens in a list box. Using visual Studio C# WindowsFormApp.
Here's my code:
private void btn3_Click(object sender, EventArgs e)
{
double n;
Drawline(out n);
}
private void Drawline(out double n)
{
n = double.Parse(textBox1.Text);
string strline = "";
for (n = 1; n <= 5; n++);
strline += '-';
lstOutput.Items.Add(String.Format(strline, n));
}
It works but no matter what number i put in the text box only one hyphen shows up. Can anyone help me?
The problem is with your for loop in DrawLine method.
You need to remove the semi-colon at the end of the for statement, so the strLine += '-'; will belong to the loop, not just be executed once.
private void Drawline(out double n)
{
n = double.Parse(textBox1.Text);
string strline = "";
for (i = 1; i <= 5; i++)
strline += '-';
lstOutput.Items.Add(String.Format(strline, n));
}
It appears you may be making this more complicated than it has to be.
It is unclear “why” the DrawLine method returns a double value using the out property? Is this a requirement? If it is not a requirement, then it is unnecessary.
Also, as per the requirement… ”Write a method called Drawline that accepts as input an integer n” … if this is the requirement, I have to ask why is the method accepting a double value? This would not fit with the requirement.
Below is a simplified version and should fit your requirements. First in the button click event, we want to get the integer value from the text box. We need to assume the user typed in a value that is NOT a valid integer. If the value is NOT a valid integer greater than zero (0), then we will display a message box indicating such.
private void button1_Click(object sender, EventArgs e) {
if ((int.TryParse(textBox1.Text, out int value)) && value > 0) {
Drawline(value);
}
else {
MessageBox.Show("String is not a number or is less than 1 : " + textBox1.Text);
}
}
Next the DrawLine method that simply adds a string of “-“ character(s) to the list box. Note the passed-in/accepted value of n has already been verified as a valid integer number greater than 0.
private void Drawline(int n) {
lstOutput.Items.Add(new string('-', n));
}
If you MUST use a for loop to generate the string, it may look something like…
private void Drawline(int n) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
sb.Append("-");
}
lstOutput.Items.Add(sb.ToString());
}
Related
I'm trying to move the first char of the string to the end every time I press the button.
My logic seems to only display the first output again and again after I press the button.
string input = "";
string manipulated = "";
int initial;
input = txtInput.Text;
if (txtInput.Text == String.Empty)
{
MessageBox.Show("Textbox is empty, please input a string.");
}
else
{
for (initial = 1; initial < input.Length; initial++)
{
manipulated += input[initial];
}
manipulated += input[0];
lblOutput.Text = manipulated.ToString();
input = manipulated;
manipulated = "";
}
E.g. if I enter "1234" in the text box and press the button, my output should be "2341", then after I hit the button again, the output should move to "3412" .. etc.
This is a simple example of Basics String operations:
private void ManipulateBtn_Click(object sender, EventArgs e)
{
string input = InputTxt.Text; // Read the text from you Textbox in Windos form
if (input == string.Empty)
{
return;
}
string temp = input[0].ToString(); // Create a temp for the first char(toString) from you input
input = input.Remove(0,1); // Remove (from you input) At Index 0 (the idex from fist char in string) 1 time)
input += temp; //add the firs item from you input at the end of string
InputTxt.Text = input; // prin the result in the Textbox back.
}
You can see the example SimpleStringOperation
You can Improve your code by another solution using Substring Method
Create a new variable called _number and set the value to 1
public partial class Form1: Form
{
private int _number = 1;
// ....
}
Then in Button event, you can replace your code with this code
private void BtnMoveText_Click(object sender, EventArgs e)
{
if (txtInput.Text == string.Empty)
{
MessageBox.Show(#"TextBox is empty, please input a string.");
return;
}
if (_number > txtInput.TextLength)
_number = 1;
lblOutput.Text = txtInput.Text.Substring(_number) + txtInput.Text.Substring(0, _number);
_number++;
#region ** Depending on Microsoft **
/*
Substring(Int32)
(Retrieves a substring from this instance. The substring starts at a specified character position and continues to the end of the string.)
Parameters
startIndex Int32
The zero-based starting character position of a substring in this instance.
.......................
Substring(Int32, Int32)
(Retrieves a substring from this instance. The substring starts at a specified character position and has a specified length..)
Parameters
startIndex Int32
The zero-based starting character position of a substring in this instance.
length Int32
The number of characters in the substring.
*/
#endregion
}
You're taking your OUTPUT and placing it in a Label...but continuing to take your INPUT from the TextBox which hasn't changed...thus the same result each time.
Simply change:
lblOutput.Text = manipulated.ToString();
To:
txtInput.Text = manipulated;
I am using this calculate function
private void Calculate()
{
double.TryParse(textBox1.Text, out num);
for (int a = 1; a <= 10; a++)
{
listBox1.Items.Add(a + " * " + num + "\n = " + a * num);
}
}
Putting Calculate() inside private void textBox1_TextChanged so it will autocalculate
I am also using :
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Back)
{
listBox1.Items.Clear();
}
}
This works but if i backspace the value inside textBox1 then when that box is empty it still shows the calculate function using a zero in the calculation displayed inside the listbox as if the empty textbox is a zero if it's empty except when i backspace again it will go away. I was wondering why that is and what the logic is behind that. So to be clear
When i enter 12 the calculate functions show 12, and if i backspace it will be 1 and it will show the calculate function as 1 but if i backspace again to make it empty it will show the calculate function as 0 inside the listbox.Here is the screenshot
Thanks for your time and help.
You don't take the result of TryParse and whatever you have (or not have) in the textbox you run the calculate code. Check if the return of TryParse is false and exit the code
If TryParse is unable to parse the input string (like in case of an empty string) it sets the out variable to its default value (zero for double) and thus you have your code running against the zero multiplier.
This happens also if the user types a not numeric value like a letter.
private void Calculate()
{
if(!double.TryParse(textBox1.Text, out num))
return;
for (int a = 1; a <= 10; a++)
{
listBox1.Items.Add(a + " * " + num + "\n = " + a * num);
}
}
I would like to know how can I add or type a number in a textbox, then this number gets saved, then add other numbers, and save them so at the end I can order them from larger to smaller and viceversa.
I got one textbox (where I type the numbers), one button (add button, that adds the typed number to the textbox2), another textbox2(where the numbers are being added simultaneously, so you can check them). There is a textbox3 (where the numbers must appear ordered from larger to smaller) and a textbox4 (where the numbers must appear ordered from smaller to larger).
Can someone help me?
Not perfect but it works. Try it.:)
//index count
int index=0;
//array declaration
string [] numbers=new string[10];
//method displaying array's content
string arrayDisplay() {
string str="";
for (int i = 0; i < numbers.Length; i++)
{
if (!(numbers[i]== "") )
{
str += numbers[i];
}
}
return str;
}
private void button1_Click(object sender, EventArgs e)
{
textBox2.Text += textBox1.Text;
index++;
if (numbers.Length >=index )
{
numbers[index] = textBox1.Text;
textBox1.Text = "";
}
//Regular sort and display
Array.Sort(numbers);
textBox3.Text = arrayDisplay();
//Reverse sort and display
Array.Reverse(numbers);
textBox4.Text = arrayDisplay();
}
I have a problem while trying to replace all text matching a particular word in a rich text box. This is the code i use
public static void ReplaceAll(RichTextBox myRtb, string word, string replacer)
{
int index = 0;
while (index < myRtb.Text.LastIndexOf(word))
{
int location = myRtb.Find(word, index, RichTextBoxFinds.None);
myRtb.Select(location, word.Length);
myRtb.SelectedText = replacer;
index++;
}
MessageBox.Show(index.ToString());
}
private void btnReplaceAll_Click(object sender, EventArgs e)
{
Form1 text = (Form1)Application.OpenForms["Form1"];
ReplaceAll(text.Current, txtFind2.Text, txtReplace.Text);
}
This works well but i have noticed a little malfunction when i try to replace a letter with itself and another letter.
For example i want to replace all the e in Welcome to Nigeria with ea.
This is what i get Weaalcomeaaaaaaa to Nigeaaaaaaaaaaaaaaria.
And the message box shows 23 when there are only three e. Pls what am i doing wrong and how can i correct it
Simply do this:
yourRichTextBox.Text = yourRichTextBox.Text.Replace("e","ea");
If you want to report the number of matches (which are replaced), you can try using Regex like this:
MessageBox.Show(Regex.Matches(yourRichTextBox.Text, "e").Count.ToString());
UPDATE
Of course, using the method above has expensive cost in memory, you can use some loop in combination with Regex to achieve some kind of advanced replacing engine like this:
public void ReplaceAll(RichTextBox myRtb, string word, string replacement){
int i = 0;
int n = 0;
int a = replacement.Length - word.Length;
foreach(Match m in Regex.Matches(myRtb.Text, word)){
myRtb.Select(m.Index + i, word.Length);
i += a;
myRtb.SelectedText = replacement;
n++;
}
MessageBox.Show("Replaced " + n + " matches!");
}
I got a code for line numbering, it works perfectly fine for numbering lines the regular way but I'm looking for something a little bit different. I want my code to only count line breaks when i press enter(the program receives an return keycode) and not then the textbox automatically cut the lines with word wrapping. This is the code i'm using right now:
//Instructions
int maxLC = 1; //maxLineCount - should be public
private void InstructionsSyncTextBox_KeyUp(object sender, KeyEventArgs e)
{
int linecount = InstructionsSyncTextBox.GetLineFromCharIndex(InstructionsSyncTextBox.TextLength) + 1;
if (linecount != maxLC)
{
InstructionsLineNumberSyncTextBox.Clear();
for (int i = 1; i < linecount + 1; i++)
{
InstructionsLineNumberSyncTextBox.AppendText(Convert.ToString(i) + "\n");
}
maxLC = linecount;
}
}
How i think i would be done easiest is by saving the line count every time someone presses enter to a list and also everytime someone presses enter it updates the line number texbox with every line number at positions said in list. But i have no idea how to detect when an return is removed. Anybody knows how to solve this?
Extremely basic example that counts the lines in your code you posted:
class Program
{
static void Main(string[] args)
{
string stringFromTextBox =
#" int maxLC = 1; //maxLineCount - should be public
private void InstructionsSyncTextBox_KeyUp(object sender, KeyEventArgs e)
{
int linecount = InstructionsSyncTextBox.GetLineFromCharIndex(InstructionsSyncTextBox.TextLength) + 1;
if (linecount != maxLC)
{
InstructionsLineNumberSyncTextBox.Clear();
for (int i = 1; i < linecount + 1; i++)
{
InstructionsLineNumberSyncTextBox.AppendText(Convert.ToString(i) + ""\n"");
}
maxLC = linecount;
}
}";
Regex r = new Regex("\r", RegexOptions.Multiline);
int lines = r.Matches(stringFromTextBox).Count;
//You'll need to run this line every time the user presses a key
}
}