I am trying to add an alert box so that the user can choose either Yes or No or Ok and Cancel, but it is not working correctly.I have to do a database check which is done in c sharp not just link that function to a button clicked event. It is my first time I am trying to do this. I am using visual studio 2010. I am not sure if my code is correct. Can anyone please guide me if I am mistaken.
private void AlertWithConfirmation()
{
Response.Write("<script language='javascript'>");
Response.Write("function onsub() ");
Response.Write("{ ");
Response.Write("return confirm(\"Are you sure?\")");
Response.Write("} ");
Response.Write("</script>");
}
This is my full C# Code:
protected void Import_Click(object sender, EventArgs e)
{
if (!Validation.ValidateDateFormat(dateField.Text))
{
errorMessageLabel.Text = "Invalid Date Format, for example: 1/1/2011 should be 01/01/2011";
}
else
{
//Validation to check if data is already imported
if (BusinessLayerHandler.isImported(dateField.Text) == false)
{
try
{
if (BusinessLayerHandler.isInProgress(dateField.Text)== true)
{
AlertWithConfirmation();
}
}
catch
{
//catch error
}
}
else if (BusinessLayerHandler.isImported(dateField.Text) == true)
{
Alert("That date was already imported");
}
}
your code is absolutely correct. only syntax error. just remove "\" before starting the double quotes in the line->
Response.Write("return confirm(\"Are you sure?\")");
replace with this line
Response.Write("return confirm("Are you sure?\")");
I don't see where you're calling the function. Why not have the function always on the page and dynamically add the function call to the button in the code behind?
Something like:
button.Attributes.Add("onclick", "onsub();");
Related
I have this function of which works fine however is there and easier way to complete the validation check using the mail address class, and would it be more fitting. Thanks in advance.
TextBox tb = new TextBox();
tb.KeyDown += new KeyEventHandler(txtEmail_KeyDown);
string strRegex = #"^(?("")("".+?(?<!\\)""#)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])#))" + #"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9][\-a-z0-9]{0,22}[a-z0-9]))";
Regex re = new Regex(strRegex); // New regex Object created
// Run Checks after the enter is pressed.
if (e.KeyCode == (Keys.Enter))
{
// checks for is match, if empty and length
if (!re.IsMatch(txtEmail.Text) || (txtEmail.Text.Equals("")) || txtEmail.Text.Length > 100)
{
// display messagebox with error
MessageBox.Show("Email not correct format!!!! ");
}
else
{
MessageBox.Show("Email Format is correct");
}
}
}
you can validate with the EmailAddressAttribute class pretty easily like this in c#
public bool ValidateEmail(string EmailToVerify)
{
if (new EmailAddressAttribute().IsValid(EmailToVerify))
return true;
else
return false;
}
but to use this you need to add this using at the top of your c# code page
using System.ComponentModel.DataAnnotations;
the only downside to this is that EmailAdressAttribute is not so permisive so it depends on what you want to restrict and permit
And if you need it here is the link the the msdn doc about this class :
https://msdn.microsoft.com/fr-fr/library/system.componentmodel.dataannotations.emailaddressattribute(v=vs.110).aspx
No, it is not stable. Since any regular expression of itself represents a finite state machine, it can, in special cases, get into an infinite loop that grafts to the server's DDOS attack.
Just use MailAddress class for validation.
UPDATE 1
After testing MailAddress class and new EmailAddressAttribute().IsValid("MAIL_TEXT_HERE")
I came to conclusion that EmailAddressAttribute's Validation is working better.
You can implement it in this way, let's say that you have TextBox and Button for submit. Just add this Click event handler to buttons Click Event:
private void button1_Click(object sender, EventArgs e)
{
if(!new EmailAddressAttribute().IsValid(textBox1.Text))
{
MessageBox.Show("Email is not valid");
}
else
{
MessageBox.Show("Email is valid");
}
}
I am making a simple hangman style game in a C# form. I have it set as textBox1_TextChanged. Except everytime the user backspaces their guess letter it takes in blank space. How can I make it so after the message saying right/wrong it clears the space. I am getting annoyed at it telling the user they made a wrong guess after they backspace. This is my first post on this forum so sorry if the code text is weird. I just want the program to clear the text in the textBox after they guess.
UPDATE: Added suggested information. Now it does everything it is supposed to do. Except it pops up a windows saying " was found in the target word". This happens if guessLetter == null || guessLetter == correct || guessLetter == false.
private void textBox1_TextChanged(object sender, EventArgs e)
{
string guessLetter = textBox1.Text;
//textBox1.ReadOnly = true;
if (targetWord == null)
{
MessageBox.Show("Please start a new game.");
textBox1.Text = ("");
}
else
{
if (targetWord.Contains(guessLetter))
{
MessageBox.Show(guessLetter + " was found in the word");
}
else
{
MessageBox.Show(guessLetter + " was not found in the word");
incorrectGuessCtr++;
textBox3.Text = incorrectGuessCtr.ToString();
}
textBox1.Text = ("");
}
}
Don't only check if the targetWord is null, but also the guessLetter. You'd better use string.IsNullOrEmpty too, since it also checks if the string is empty:
if (!string.IsNullOrEmpty(targetWord) && !string.IsNullOrEmpty(guessLetter))
{
...
}
I guess you should also check if there is exactly one letter entered. That would mean this additional check:
if (guessLetter.Length == 1)
{
...
}
You will enter this event when you write code that changes Text property in textbox. I mean this.
textBox3.Text = incorrectGuessCtr.ToString();
Put something in function arguments or set some flags so that you can identify whether the event is called from user input or your clearing the text.
Just check how many times this function is called when user press backspace. You will get the idea.
I have just started programming in C#. I am trying to convert a string to int. Like this:
int.Parse(textBox1.Text);
This is working fine when I enter a value but this is giving me exception when nothing is entered and I press the button. What should I do? Is there a function to solve this? Thanks
Use int.TryParse instead, it doesn't throw exception if the parsing fails.
Converts the string representation of a number to its 32-bit signed integer equivalent. A return value indicates whether the conversion succeeded.
int number;
bool isValid = int.TryParse(textBox1.Text, out number);
if(isValid)
{
// parsing was successful
}
One way to approach this is by using int.tryParse() instead of just int.Parse(). You can then check the result to see if the input was in the correct format.
Here is a sample:
int userInput;
if(!int.TryParse(textBox1.Text, out userInput))
{
//error in input here
}
After executing, if int.TryParse() returns true, then you will have a valid value in the userInput variable.
Alternatively you can wrap it in a try-catch, but it is better to attempt the parse and handle it without exceptions if possible.
Put this following code under your button event. It will make sure that the text/numbers entered into the textbox are able to be converted into an integer. Also, it will make sure that the textbox has numbers/text entered.
if (textBox1.Text != "")
{
try
{
Convert.ToInt32(textBox1.Text);
}
catch
{
/*
Characters were entered, thus the textbox's text cannon be converted into an integer.
Also, you can include this line of code to notify the user why the text is not being converted into a integer:
MessageBox.Show("Please enter only numbers in the textbox!", "PROGRAM NAME", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
*/
}
}
/*
else
{
MessageBox.Show("Please enter numbers in the textbox!", "PROGRAM NAME", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
*/
This is simple. You can do this on your button click event:
int number;
if (int.TryParse(textbox1.Text, out number))
{
// number is an int converted from string in textbox1.
// your code
}
else
{
//show error output to the user
}
Try below given solution
<script type="text/javascript">
function myFunction() {
alert('Please enter textbox value.');
}
</script>
And in the button click event use below given logic.
if (TextBox1.Text == "")
{
//Call javascript function using server side code.
ClientScript.RegisterStartupScript(this.GetType(), "CallMyFunction", "myFunction()", true);
}
else
{
int value;
value = int.Parse(TextBox1.Text);
}
I just started trying to learn C#. I've read probably 50 tutorials so far and thought I had a good understanding. Apparently I was wrong. I've been doing a lot of reading on msdn.microsoft.com's C# Programmer's Reference but it's seeming to not be the best source for tutorials.
I'm literally trying to accomplish the most simplest of tasks. Trying to understand variables, manipulation, and inputs. I come from web programming and want to turn a PHP script into a desktop application so I'm trying to learn the basics of C# and I think I might need to learn a different language instead.
Basically, I have a textbox and a button. When the button is clicked, I want to check the text in the textbox and see if it matches a certain string. Then display a message box with a message.
private void btnClick_Click(object sender, EventArgs e) {
if(txtCL.Text == "one") {
bool myTest = true;
} else {
bool myTest = false;
}
if(myTest == true) {
MessageBox.Show("You entered the correct password.", "Important Message");
} else {
MessageBox.Show("The password you entered is not correct.", "Incorrect Input");
}
}
Would really appreciate if someone could point me to better tutorials so I can learn quicker. Microsoft's documentation really hasn't taught me anything really.
I apologize for the stupid question, feel free to call me an idiot.
It's a scoping issue, myTest does not exist, at least not down there - you're creating it each time within the scope of each of your initial conditions. If you do:
bool myTest = false;
if(txtCL.Text == "one") {
myTest = true;
}
if(myTest == true) {
MessageBox.Show("You entered the correct password.", "Important Message");
} else {
MessageBox.Show("The password you entered is not correct.", "Incorrect Input");
}
Then you're specifying your boolean value, and setting it to false (which is the default value for a bool anyway, actually), then checking if your condition is met and reassigning it accordingly; it can then be evaluated to show your message box.
You could shorten this code yet more, an exercise for the reader. (:
you don't really need a bool variable, you can make it simplier:
private void btnClick_Click(object sender, EventArgs e)
{
if(txtCL.Text == "one")
{
MessageBox.Show("You entered the correct password.", "Important Message");
}
else
{
MessageBox.Show("The password you entered is not correct.", "Incorrect Input");
}
}
and if you need some tutorials, just google "C# beginner tutorials" or if you prefer video tutorials, you can take a look here.
if(...) {
bool myTest = true;
} else {
bool myTest = false;
}
// At this point in time 'myTest' is not a known variable.
// It's out of scope already s your next line will cause a compile error.
if(myTest == true) {
...
}
So you need to declare the variable in scope
bool myTest = false;
if(...) {
myTest = true;
}
// Now you can use the myTest variable
if(myTest) {
...
}
As you already pointed out, you don't need the variable at all, since this would work all the same
private void btnClick_Click(object sender, EventArgs e) {
if(txtCL.Text == "one") {
MessageBox.Show("You entered the correct password.", "Important Message");
} else {
MessageBox.Show("The password you entered is not correct.", "Incorrect Input");
}
}
You can read as many books as you like, but since you already have programming experience with PHP I'd suggest to get more hands on experience with C#. In parallel a book of course does not hurt. But I think the approach you are following (reading online, coding stuff) will pay off in the end. Give it some time. Practice. A lot.
i am assuming that nothing is happening when you click the button. is this true? if it is, put a break point at the line: if(txtCL.Text == "one") , run the app and click it. If you do not hit the break point then there is no linkage between the 'click' event and your code. Explore the button properties and you will see a way to make the linkage.
stick with it, i was a PHP guy and now a C# guy. It can be done.
Not sure if i will be able to formulate my question quite clear but let me try:
So i've written a small piece of code which will give the user the option to select a desired status for his Office Communicator when his PC get locked ( by default it goes automatically on status "away" ) .So here it is the Windows Form wich is basically a combobox and a button .The Combo has four option "Away" , "Busy" , Do not Disturb" and "Online" respectively. All seems fine and the program compiles ok.The Menu appears , you select the status you wish , push the button and then lock your PC - so far all goes perfect.Your Status is as selected .And now comes the Problem.You unlock your PC and try to select a different status , same actions , but when you lock the PC it still shows the previously selected status here is the Button_Click method
public void Btn_Click(Object sender, EventArgs e)
{
// When the button is clicked,
// change the button text, and disable it.
if (Comb.Text == "Away")
{
MessageBox.Show("Saved ! \nYour Status will be 'Away' ");
Method2();
}
else if (Comb.Text == "Busy")
{
MessageBox.Show("Saved ! \nYour Status will be 'Busy' ");
Method1();
}
else if (Comb.Text == "Do Not Disturb")
{
MessageBox.Show("Saved ! \nYour Status will be 'Do Not Disturb' ");
Method3();
}
else
{
MessageBox.Show("Saved ! \nYour Status will be 'Online' ");
Method4();
}
But.Enabled = true;
// Display the greeting label text.
}
So the 4 methods ( Method1 () , 2 ... etc ) are the one to change the status depending on the text in the combo box drop down menu ( the status you select )i have tested all methods separately from each other and they work beautiful thereforfe i exclude a problems with them , is it some logical error ?
Nikolay, give SharpDevelop's debugger a try. In your code's margin click once next to the line if (Comb.Text == "Away") and then hover over the variable names to see what they are set to each time it runs. You can use the "Step over" "Step into" and "Step out" functions to "Execute the highlighted method without looking at the internals", "Debug the Internals of a method" or "Run the current method to the end and then show the next level up" respectively.
If you do this you'll figure out why you're getting an error and it will be MUCH easier to determine where the error is coming from. (For instance, if a variable is set to an unexpected value you'll know to figure out when that changed).
static void SystemEvents_SessionSwitch1(object sender, SessionSwitchEventArgs e)
{
if (e.Reason == SessionSwitchReason.SessionLock)
{
System.Threading.Thread.Sleep(500);
CommunicatorAPI.MessengerClass comm = new CommunicatorAPI.MessengerClass();
if (comm.MyStatus==MISTATUS.MISTATUS_AWAY)
{
SetMyPresence1 ();
} else if (e.Reason == SessionSwitchReason.SessionUnlock)
{
ChangeStatus1 ();
}
}
}