Matching brackets and indentation in RichTextBox using C#? [closed] - c#

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I want to make a Code Editing control that can format text somewhat like Visual Studio,till now i have implemented syntax highlighting and autocompletion but i want to format text in nested curly braces.For example:Consider a for loop,
for(int i=0;i<=10;i++)
{
Function_One(); //This should be a tab away from first brace
Function_Two(); //So with this
if(a==b) //So with this
{ //This should be four tabs away from first brace
MessageBox.Show("Some text");//This should be six tabs away from first brace
} //This should be four tabs away from first brace
}
now what i want is that this should look something like this,
for(int i=0;i<=10;i++)
{
Function_One();
Function_Two();
if(a==b)
{
MessageBox.Show("Some text");
}
}
I have already tried Regular Expressions but at some point they fail to match,so i tried to match it with code but code cannot match very deeply nested code or is very hard to implement
,so is there any way to achieve this,and one more thing i am doing all this in Winforms control RichTextBox using C#.

This is by no means a simple feat, I am unaware of any tools or plugins that you would be able to take advantage of, my only recommendation is to research Monodevelop's implementation of this.
See MonoDevelop's github for details.

I think the best way to implement this would be to create some global variables for your form:
private int _nestedBracketCount = 0;
private const string TabString = " ";
private const int TabSpaces = 4;
And then handle all of it in a KeyPressed event handler for the rich text box:
private void richTextBox1_OnKeyPress(object sender, KeyPressEventArgs e) {
var currentLength = richTextBox1.Text.Length;
if (e.KeyChar == '{') {
// need to increment bracket counter
_nestedBracketCount++;
} else if (e.KeyChar == '}') {
// remove last #(TabSpaces) characters from the richtextbox
richTextBox1.Text.Remove(currentLength - TabSpaces);
_nestedBracketCount--;
richTextBox1.AppendText("}");
e.Handled = true;
} else if (e.KeyChar == (char)13) {
// append newline and correct number of tabs.
var formattedSpaces = string.Empty;
for (var i = 0; i < _nestedBracketCount; i++)
formattedSpaces += TabString;
richTextBox1.AppendText("\n" + formattedSpaces);
e.Handled = true;
}
}
I think this should provide you with a halfway decent starting point.

Related

Unity3D with C# - Using Input field to answer question [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I'm creating a unity quiz game using input fields.
How can I use text from an input field to match with an answer in a c# script?
hijinxbassist's example is good, however, i made an example that includes the other parts as well, like adding event listeners and declaring the fields.
Checking for single correct answer:
public Button submitAnswerBtn; // assign a UI button object in editor
public InputField answerInput; // assign a UI inputfield object in editor
private string a1_right_answer = "foo"; // make it public and edit the answer in editor if you like
private void Awake()
{
// add event listener when button for submitting answer is clicked
submitAnswerBtn.onClick.AddListener(() => {
// validate the answer
if(answerInput.text.ToLower() == a1_right_answer) {
// success
Debug.Log("Correct");
} else {
Debug.Error("Wrong");
}
});
Checking for multiple correct answers:
public Button submitAnswerBtn; // assign a UI button object in editor
public InputField answerInput; // assign a UI inputfield object in editor
private string[] a1_right_answers = { "foo", "bar", "foo1", "bar1" }; // multiple right answers
private bool is_right_answer = false; // default value
private void Awake()
{
// add event listener when button for submitting answer is clicked
submitAnswerBtn.onClick.AddListener(() => {
// loop through all the right answers
for (int i = 0; i < a1_right_answers.Length; i++)
{
// validate the answer
if(answerInput.text.ToLower() == a1_right_answers[i]) {
// success
is_right_answer = true;
break;
}
}
// check if the user got the right or wrong answer
if(is_right_answer) {
Debug.Log("Correct");
is_right_answer = false; // reset for next guess
}
else {
Debug.Log("Wrong");
// no need to reset 'is_right_answer' since its value is already default
}
});
I am not sure which part of this problem you are stuck on, but I will attempt to answer.
I think the most important thing when comparing an input field with a stored answer is to make sure the comparison is case insensitive. You can do this by converting both texts to either lowercase or uppercase.
var usersAnswer = answerInputField.text.ToLower();
var actualAnswer = "Some Answer".ToLower();
if (usersAnswer == actualAnswer)
{
Debug.Log("You got it right!");
}

The Code Won't Execute all [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I have the following code:
private void G1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
decimal quantity = 0, cost = 0;
decimal totalstock = 0, newtotalstock = 0;
if (decimal.TryParse(G1.Rows[e.RowIndex].Cells["RealExport"].Value.ToString(), out quantity) && decimal.TryParse(G1.Rows[e.RowIndex].Cells["Cost"].Value.ToString(), out cost))
{
decimal price = quantity * cost;
G1.Rows[e.RowIndex].Cells["Total"].Value = price.ToString();
}
if (decimal.TryParse(G1.Rows[e.RowIndex].Cells["TotalStock"].Value.ToString(), out totalstock) && decimal.TryParse(G1.Rows[e.RowIndex].Cells["RealExport"].Value.ToString(), out quantity))
{
newtotalstock = totalstock - quantity;
G1.Rows[e.RowIndex].Cells["TotalStock"].Value = newtotalstock.ToString();
return;
}
decimal avai = 0, newavai = 0;
if (decimal.TryParse(G1.Rows[e.RowIndex].Cells["RealExport"].Value.ToString(), out quantity) && decimal.TryParse(G1.Rows[e.RowIndex].Cells["AvailableStock"].Value.ToString(), out avai))
{
newavai = avai - quantity;
G1.Rows[e.RowIndex].Cells["AvailableStock"].Value = newavai.ToString();
return;
} }
The problem is, it only execute 2 out of 3 the code, I mean, when the newtotalstock is calculated, the code will end.
I try to change the newavai to up above, and the result is the same, it will calculate the newavai and pass the newtotalstock. I dont know why, all the code are correct. Please help
word "return" ends function, if you are using void type method you don't really need to use return, unless you want to quit it at certain point. The code after "return" will never be executed (only exception might be during usage "yield return", but that is another story).
void someMethod()
{
doSomething();
return;
StartWorldWarThree(); //no waries, this will never be executed :)
}
Furethermore you can always make a breakpoint in your code (click on the left border of your window, or just read about it) and then check how your code is being executed :) F10/F11 to make step in your code, F5 to go to next breakpoint or end execution, if there are no more breakpoints.
Taking in count that all conditions are true the return; will stop executing the rest of the code, if you want the 3 if to be executed, remove the return; and place it the last line of the method as
void Method() {
if() {}
if() {}
if() {}
return;
}
Or dont place it at all, because that method is void and does not need it

c# when pressing a button add totals together [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
When i press "buttonTotal" i need it to add fuel prices together. I have lblDailyPrice, lblTotalLitresEntered and i have 3 buttons "unleaded"; "Diesel"; "Premium"... any help as to how i can achieve this?
private void btnTotal_Click(object sender, EventArgs e)
{
try
{
if(btnUnleaded_Click)
{
}
else if (btnDiesel_Click)
{
}
else if (btnPremium_Click)
{
}
}
catch
{
}
}
I would advise making the "unleaded", "Diesel", "Premium" options RadioButtons instead of Buttons and bind them under a container like Panel. So, when the user presses the "buttonTotal" the program will check which RadioButton is checked and then calculate the corresponding value.
private void btnTotal_Click(object sender, EventArgs e)
{
double totalPrice = 0;
if(unleadedRadioButton.Checked)
{
totalPrice = lblDailyPrice * lblTotalLitresEntered * unleadedValue;
}
else if (dieselRadioButton.Checked)
{
totalPrice = lblDailyPrice * lblTotalLitresEntered * dieselValue;
}
else if (premiumRadioButton.Checked)
{
totalPrice = lblDailyPrice * lblTotalLitresEntered * premiumValue;
}
}
I'm assuming your using Windows Forms. I have linked relevant documentation on how to accomplish this task. With just a tiny bit of reading, it should be easy. Good luck and welcome to StackOverflow!.
Get the prices from the labels.
Convert those strings into a number type with a decimal.
Then just do the math on the resulting variables.
Example:
var total = Convert.ToDecimal(lblDailyPrice.Text) * Convert.ToDecimal(lblTotalLitresEntered.Text);

C# TextBox that allows a maximum of one dot [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
How can I make a TextBox in C# to allow a maximum of one . (dot)?
Thus, abcdef and abc.def would be valid inputs whereas ab.cd.ef wouldn't.
By allow I mean that the user should not be able to enter a dot if there is already one in the text field.
Java has DocumentFilters for that purpose, is there something similar in C#?
I guess this is for validating user inputs. You should create a button and tell the user when he is done, press it so that you can check whether there is only one . in the string.
Assumptions:
Let your text box be called tb. Let your button's Click event handler be BtnOnClick.
Now we can start to write code. First create the handler:
private void BtnOnClick (object sender, EventArgs e) {
}
In the handler, you need to loop through the string and check each character. You can use a foreach for this:
int dotCount = 0;
string s = tb.Text;
if (s.StartsWith(".")) //starts with .
//code to handle invalid input
return;
if (s.EndsWith(".")) //ends with .
//code to handle invalid input
return;
foreach (char c in s) {
if (c == '.') {
dotCount++;
}
if (dotCount >= 2) { //more than two .
//code to handle invalid input
return;
}
}
// if input is valid, this will execute
Alternatively, you can use a query expression. But I think you are unlikely to know what that is.
string s = tb.Text;
if (s.StartsWith(".")) //starts with .
//code to handle invalid input
return;
if (s.EndsWith(".")) //ends with .
//code to handle invalid input
return;
var query = from character in s
where character == '.'
select character;
if (query.Count() > 1) {
//code to handle invalid input
return;
}
// if input is valid, this will execute

Can't stop a timer in c# [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I want the timer to stop when the ImageNumber is equal to zero.
private void Health_Regen_Tick(object sender, EventArgs e)
{
if (ImageNumber1 == 0)
Health_Regen.Enabled = false;
if (ImageNumber1 < 20)
{
ImageNumber1++
HealthBar.Image = Image.FromFile(path + ImageNumber1.ToString() + ".png");
}
}
If I add a return statement after the first if statement the second if statement is disabled.
I want the timer to stop when the ImageNumber is equal to zero.
You appear to already know how to do this, assuming Health_Regen is a Timer then:
Health_Regen.Enabled = false;
Will disable your Timer.
If I add a return statement after the first if statement the second if statement is disabled.
That is to be expected as you are using the return keyword which will prevent anything after it within the same code block from being executed.
Your question does not make exactly what you are asking clear, however, I am assuming from your comment that the second if statement is not executed that you want to update the HealthBar.Image value even if the Timer is disabled? If so then something like below should work for you
private void Health_Regen_Tick(object sender, EventArgs e)
{
if (ImageNumber1 == 0)
{
Health_Regen.Enabled = false;
}
else if (ImageNumber1 <= 20)
{
ImageNumber1 += 1;
}
HealthBar.Image = Image.FromFile(path + ImageNumber1.ToString() + ".png";
}
You should just be able to call the Stop method on the timer instance.
if (ImageNumber == 0)
{
Health_Regen.Stop();
}
This is just a guess!.
Replace
if (ImageNumber1 == 0)
with
if (ImageNumber1 >= 20)
Your timer will already stop when ImageNumber1 equals 0, but it just never counts down to 0.
Also if you change ImageNumber1 to 0. It may already be running the timer which will increment it by one and skip the stopper, so pretty much the way you have it coded it's based on luck right now.
The luck happens if you change ImageNumber1 while timer is already running.
Try this:
if (ImageNumber1 == 0)
Health_Regen.Enabled = false;
else if (ImageNumber1 < 20)
{
ImageNumber1++;
HealthBar.Image = Image.FromFile(path + ImageNumber1.ToString() + ".png");
}
Still the luck may still happen best you can do is stop the timer outside the timer when you make it ImageNumber1 = 0;
Best Fix:
Also a better solution is to fix your program to start at ImageNumber1 = 20 and just keep going down to 0.. when it hits 0 stop the timer.. you shouldn't make it this confusing all you will have to do is rename a few png files in a new order! instead of
1.png now it will be 20.png
2.png now it will be 19.png
and so on and so on..

Categories

Resources