Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
protected void Button1_Click(object sender, EventArgs e)
{
if (username.Text == "test" && password.Text == "test")
Response.Cookies ["TheCookie"]["Username"] = username.Text;
Response.Redirect("loggedIn.aspx");
else
Label1.Text = "Invalid Username and/or Password.";
}
Above is a function I'm trying to make happen. For some reason the else statement here isn't being accepted. I don't know why. Any help would be appreciated.
if (username.Text == "test" && password.Text == "test")
{
Response.Cookies ["TheCookie"]["Username"] = username.Text;
Response.Redirect("loggedIn.aspx");
}
else
Label1.Text = "Invalid Username and/or Password.";
Wrap it with braces, otherwise it'll take only the next immediate line (statement) as part of the condition.
It's a good practice to do that even for a one line if/else because it makes maintenance easier.
else
{
Label1.Text = "Invalid Username and/or Password.";
}
if-else (C# Reference) - MSDN
Both the then-statement and the else-statement can consist of a single
statement or multiple statements that are enclosed in braces
({}). For a single statement, the braces are optional but
recommended.
You have multiple statements in the then (true) part of if statement. Although you have used indentation, but those spaces/indents will not be considered by the compiler. Since you haven't specified {} to define scope of if statement, only a single statement is considered for if scope. Hence the error.
You can fix that by introducing scope with {}. It is also recommended to use {} (explicitly define scope) for single statement , as it makes code easier to understand and less prone to error. You code should be:
protected void Button1_Click(object sender, EventArgs e)
{
if (username.Text == "test" && password.Text == "test")
{
Response.Cookies["TheCookie"]["Username"] = username.Text;
Response.Redirect("loggedIn.aspx");
}
else
{
Label1.Text = "Invalid Username and/or Password.";
}
}
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I'm having some difficulty making two separate functions inside the same MouseClick Eventhandler on a checkbox in C# using Winforms.
If the user clicks the checkbox it's supposed to come a warning for the user to verify the action. If the user un-checks the checkbox a different warning will show for the user to verify the action.
My code is the following:
private bool alreadyClicked = false;
private void myCheckbox_MouseClick(object sender, MouseEventArgs e)
{
if (!myCheckbox.Checked && !alreadyClicked)
{
DialogResult d1 = MessageBox.Show("Some text1", "Some title1", MessageBoxButtons.YesNo);
if (d1 == DialogResult.Yes)
{
myCheckbox.Checked = true;
alreadyClicked = true;
}
else
{
myCheckbox.Checked = false;
}
}
if (myCheckbox.Checked && alreadyClicked)
{
DialogResult d2 = MessageBox.Show("Some text2", "Some title2", MessageBoxButtons.YesNo);
if (d2 == DialogResult.Yes)
{
myCheckbox.Checked = false;
alreadyClicked = false;
}
else
{
myCheckbox.Checked = true;
}
}
}
The problem is that the second if-statement checking if the checkbox is checked and if the "alreadyClicked"-variable is true triggers when the user verifies the first action (to check the checkbox), which happens due to the "alreadyClicked"-variable being true before the event closes. I'm stuck and would appreciate any help.
Thanks in advance.
Well let's look at the two if statements.
When the checkbox is first clicked and the first messagebox will be answered with yes, you set the checkbox and the alreadyClicked variable to true. Right afterwards in the second if statement you check if those two values are true. Which they are of course because we just set them to true. Therefore the second if statement will be true and the second message will be displayed.
To prevent this behaviour you could use an else if (myCheckbox.Checked && alreadyClicked) after the first if statement. In that case the second if statement will only be processed, when the first one results to false.
You could also consider if the bool variable alreadyClicked is really adding any value here. As of my understanding it always has the same value as the checkbox itself.
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
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
I just try to make
if (txtNo.Text != "" || txtName.Text != "" || txtAddress.Text != "")
{
MessageBox.Show("Please Fill Textbox");
}
I just click update with not value in textbox.
I just make clear when the textbox in the user press the update button, then the warning messages are displayed so that the user recharges. Without being subject to error or out of the program, I am using SQL SERVER to save data.
Your error states that your SQL Connection is not set up properly. Wrap your SQL command in a using statement with a SQL connection. You will need to supply a valid connection string to your database.
using (SqlConnection con = new SqlConnection(connectionString))
{
SqlCommand cmd ...
cmd.ExecuteNonQuery() ...
}
Error is not related to textbox.text value.It is related to sqlcommand.
Please note that whenever you are using sqlcommand. you have to declare new sqlconnection object with connection string. And then apply it to sqlcommand.
Please check below query for example
https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand(v=vs.110).aspx
Your problem is not the string, which I would recommend you to use String.IsNullOrEmpty("YOURSTRING")
You have a problem with you database connection. Set this up properly, creating an instance of SQLConnection and try again.
Change your button code like this.
private void btnUpdate_Click(object sender, EventArgs e)
{
if (txtNo.Text == "" || txtName.Text == "" || txtAddress.Text == "")
{
MessageBox.Show("Please Fill TextBox");
return;
}
SqlCommand CMD = new SqlCommand(UPDATE...
Connection.Buka.....();
CMD.ExecuteNonQuery();
MessageBox.Show(....)
Connection.Tutu.....();
}
comparing strings with the .Equals() method instead of the == operator is best practice, may not solve your problem but the code will be cleaner
if((!string.isnullorwhitespace(txtNo.Text)) || (!string.isnullorwhitespace(txtName.Text)) ||(!string.isnullorwhitespace(txtAddress.Text)))
{
enter code here
}
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 8 years ago.
Improve this question
What is the problem to my code? It always results in "No record found!" even if what am I searching is correct.
private void button3_Click(object sender, EventArgs e)
{
string[] lines = System.IO.File.ReadAllLines(#"C:\Users\kulet\Desktop\file.txt");
System.Console.WriteLine("Contents of file.txt = ");
foreach (string line in lines)
{
if (textBox14.Text == line)
{
label28.Text = "File exists!";
}
else
{
label28.Text = "No record found!";
}
Console.WriteLine("\t" + line);
}
You should place a break; after you found a match, since now it will always show the match of the last line:
label28.Text = "File exists!";
break;
The break will bail out of the foreach.
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.