DialogResult Infinite Loop - while-loop

So I have this project at school to create a game "Guess the number". I am trying to loop a DialogResult using a switch statement and a while loop. I tried many possibilities but I go into a infinite loop. Just to know I am a beginner.I would really need some help here if possible. This is my code. Thanks in advance.
private void btnStartTheGame_Click(object sender, EventArgs e)
{
int guessTheNumber = Convert.ToInt32(txtNumberGuess.Text);
DialogResult dialogResult = MessageBox.Show("Is number" + number.ToString() + " you are thinking about?", "Answer the question!", MessageBoxButtons.YesNo);
switch(dialogResult)
{
case DialogResult.No:
while (dialogResult == DialogResult.No)
{
Random newNumberGenerator = new Random();
number = newNumberGenerator.Next(0, 101);
MessageBox.Show("Is number" + number.ToString() + " you are thinking about?", "Answer the question!", MessageBoxButtons.YesNo);
}
break;
case DialogResult.Yes:
if (dialogResult == DialogResult.Yes)
{
MessageBox.Show("Congratulation! You guessed the number!!");
break;
}
break;
}

You need to load the new result of the dialog.
int guessTheNumber = Convert.ToInt32(txtNumberGuess.Text);
DialogResult dialogResult;
do
{
Random newNumberGenerator = new Random();
number = newNumberGenerator.Next(0, 101);
dialogResult = MessageBox.Show("Is number" + number.ToString() + " you are thinking about?", "Answer the question!", MessageBoxButtons.YesNo);
} while (dialogResult == DialogResult.No);
MessageBox.Show("Congratulation! You guessed the number!!");
The do loop will execute the code first, and then check the condition. THis will also prevent having the same piece of code at different places, meaning the same.

Related

How can i close window and relaod in asp.net

My code look like below.
protected void btnApprove_Click(object sender, EventArgs e)
{
if (id == "Button2")
{
string sql = #"update AdjTranSeqDetails set Approver1Status = 'Rejected',finalStatus='Rejected' ,updatedtime = GETDATE(),Approver1Comment ='{1}',modifieduser = '{2}' where TranSeq ={0}";
sql = String.Format(sql, tbxTranSeq.Text, TextBox2.Text, Master.CurrentUser);
string sql2 = #"INSERT INTO AdjTranSeqDetailsHistory SELECT * FROM AdjTranSeqDetails WHERE tranSeq={0}";
sql2 = String.Format(sql2, tbxTranSeq.Text);
string sql3 = #"delete from AdjTranSeqDetails where tranSeq={0}";
sql3 = String.Format(sql3, tbxTranSeq.Text);
if (dba.SqlUpdate(sql, ref ex, ref rowCt) || dba.SqlInsert(sql2, ref ex, ref rowCt) ||dba.SqlDelete(sql3, ref ex, ref rowCt))
{
string sscript = "<script language=\"Jscript\" > ";
if (Master.PageMode == "View")
{
sscript += "if (window.opener && !window.opener.closed) ";
sscript += "{window.opener.DoSearch();}";
}
sscript += "window.opener='x';self.close();";
sscript += "</Script>";
Page.ClientScript.RegisterStartupScript(this.GetType(), "SelfClose", sscript);
}
}
updateapp();
GetBillTranInfo();
}
Like Button2, like have 10 button. If one if condition function done I need to close the window and need to reload the page. Can I do like this?
I have tried like above but that is not working for me.
In my user controls, after updating data I do:
Response.Redirect(Request.RawUrl);
That ensures that the page is reloaded, and it works fine from a user control. You use RawURL and not Request.Url.AbsoluteUri to preserve any GET parameters that may be included in the request.
You probably don't want to use: __doPostBack, since many aspx pages behave differently when doing a postback.

New line "\n" does not work yet no errors are given

I have a program that loads a checked list box, then the user selects the items they want and selects a button to say they are done. The checked items are read in a contiguous string with a newline "\n" at the end of each string added. My problem is everything works ok except the newline "\n", and I don't know why.
Code
private: System::Void bntSelected_Click(System::Object^ sender, System::EventArgs^ e) {
int numSelected = this->checkedListBox1->CheckedItems->Count;
if (numSelected != 0)
{
// Set input focus to the list box.
//SetFocus(lstReceiver);
String^ listBoxStr = "";
// If so, loop through all checked items and print results.
for (int x = 0; x < numSelected; x++)
{
listBoxStr = listBoxStr + (x + 1).ToString() + " = " + this->checkedListBox1->CheckedItems[x]->ToString() + "\n";
}
lstReceiver->Items->Add(listBoxStr);
}
}
The string is being formed correctly, but the ListBox control doesn't show newlines in its list items - each item is pushed onto a single line. You can see this by debugging, or by adding a Label to the form with AutoSize set to false - the label will show the newline(s) in the string properly.
Related (C#): How to put a \n(new line) inside a list box?
Instead of ā€˜\nā€™, try ā€˜\r\nā€™. This may be a windows thing.

PL/SQL - Aggregate values & Write to table

I am just starting to dabble in PL/SQL so this question may be very straightforward. Here is the scenario:
I have several checkboxes which carry a weighted numeric value. For example:
Checkbox I --> Value '5'
Checkbox II --> Value '10'
Checkbox III --> Value '15'
etc.
The form would have 15 checkboxes in total and the end-user can select anywhere from 0 to all 15. As they select the checkboxes, the total weight would get calculated and a final numeric value would be displayed. For example. checking off 3 Checkbox I & 2 Checkbox III would = 45 points.
Now the total value of 45 would equal to a separate value. Example:
At 0 points, value = 'Okay'
1-15 points, value = 'Error'
16-30 points, value = 'Warning'
31+ points, value = 'Critical'
The form itself is built within Oracle APEX and I can do it using Dynamic Actions but using PL/SQL may be a better solution.
In summary, I'd like the hidden field to first calculate the total from the checked checkboxes and then use that total to figure out the value of either Okay, Error, Warning, or Critical.
Any assistance is much appreciated!
In my experience, it is better if we're going to use javascript on your case since we have to manipulate DOM and events of the checkboxes. If you want to display/change item values and get values at runtime, then javascript is better in doing that than PLSQL unless you want to submit your page every time you check/uncheck a box in your page which is not advisable.
Here is my solution for your question.
First, create a Display Only item on your page. This is where the values "Okay", "Error", "Warning", or "Critical" will appear. And its very important to set it's default value to 0. Then inside your page's "Function and Global Declaration" part, put the following functions:
function getcheck(checkbox_id,displayOnly_id){
var chkboxName = document.getElementById(checkbox_id + "_0").getAttribute("name");
var chks = document.getElementsByName(chkboxName);
var howmanychecks = chks.length;
var currentSum=0;
var v_remarks = "";
for(x=0;x<howmanychecks;x++){
chks[x].setAttribute("onchange","checkIfchecked(this,\'" + displayOnly_id + "\')");
if(chks[x].checked){
currentSum = currentSum + Number(chks[x].value);
}
}
if(currentSum==0){
v_remarks = "Okay";
}
else if(currentSum>0 && currentSum<=15){
v_remarks = "Error";
}
else if(currentSum>15 && currentSum<=30){
v_remarks = "Warning";
}
else{
v_remarks = "Critical";
}
document.getElementById(displayOnly_id).value = currentSum;
document.getElementById(displayOnly_id + "_DISPLAY").innerHTML = currentSum + ": " + v_remarks;
}
function checkIfchecked(p_element, displayOnly_id){
var v_difference;
var v_sum = Number($v(displayOnly_id));
var displayOnly_display = displayOnly_id + "_DISPLAY";
var v_remarks = "";
if(p_element.checked){
v_sum = v_sum + Number(p_element.value);
$("#" + displayOnly_id).val(v_sum);
}
else{
v_difference=Number($("#" + displayOnly_id).val())-Number(p_element.value);
if(v_difference<0){
v_difference=0;
}
$("#" + displayOnly_id).val(v_difference);
}
if($("#" + displayOnly_id).val()==0){
v_remarks = "Okay";
}
else if($("#" + displayOnly_id).val()>0 && $("#" + displayOnly_id).val()<=15){
v_remarks = "Error";
}
else if($("#" + displayOnly_id).val()>15 && $("#" + displayOnly_id).val()<=30){
v_remarks = "Warning";
}
else{
v_remarks = "Critical";
}
document.getElementById(displayOnly_display).innerHTML=$("#" + displayOnly_id).val() + ": " + v_remarks;
}
The above functions will get the sum of the values of those boxes that are checked. A value of a box will be taken out of the current sum if it is unchecked as well. It will also display the remarks for the current checked points whether if it is "Okay", "Error", "Warning", or "Critical".
In your "Execute when Page Loads" part of your page, add the following line:
getcheck(nameofyourcheckboxitem,nameofyourdisplayonlyitem);
where nameofyourcheckboxitem is the name of your Check Box and nameofyourdisplayonlyitem is the name of the Display Only item you have just created.
Here's a sample line on how to use the function that I've given you:
getcheck("P1_MYCHECKBOX","P1_MYDISPLAYONLY");

Column is not indexed even though it is. PreparedStatement inside

I'm really struggling with a bug that did not appear on my dev environment, only once deployed in test.
I'm using a prepared Statement to run around 30 000 query in a row. The query check for the similarity of a string with what's in our database, using the oracle fuzzy method.
The column checked is indexed, but, don't know why, it fails randomly after some iterations, saying that index does not exists.
I don't understand what's going on, as the index really exists. My method never rebuild or delete the index so there is no reason for this error to appear ...
public List<EntryToCheck> checkEntriesOnSuspiciousElement(List<EntryToCheck> entries, int type,int score, int numresults, int percentage) throws Exception {
Connection connection = null;
PreparedStatement statementFirstName = null;
PreparedStatement statementLastname = null;
int finalScore = checkScore(score);
int finalNumResults = checkNumResults(numresults);
int finalPercentage = checkPercentage(percentage);
try {
connection = dataSource.getConnection();
StringBuilder requestLastNameOnly = new StringBuilder("SELECT SE.ELEMENT_ID, SE.LASTNAME||' '||SE.FIRSTNAME AS ELEMENT, SCORE(1) AS SCORE ");
requestLastNameOnly.append("FROM BL_SUSPICIOUS_ELEMENT SE ");
requestLastNameOnly.append("WHERE CONTAINS(SE.LASTNAME, 'fuzzy({' || ? || '},' || ? || ',' || ? || ', weight)', 1)>? ");
requestLastNameOnly.append((type > 0 ? "AND SE.ELEMENT_TYPE_ID = ? " : " "));
requestLastNameOnly.append("ORDER BY SCORE DESC");
statementLastname = connection.prepareStatement(requestLastNameOnly.toString());
for (EntryToCheck entryToCheck : entries) {
ResultSet rs;
boolean withFirstName = (entryToCheck.getEntryFirstname() != null && !entryToCheck.getEntryFirstname().equals(""));
statementLastname.setString(1, entryToCheck.getEntryLastname().replaceAll("'","''"));
statementLastname.setInt(2, finalScore);
statementLastname.setInt(3, finalNumResults);
statementLastname.setInt(4, finalPercentage);
if(type > 0){
statementLastname.setInt(5, type);
}
System.out.println("Query LastName : " + entryToCheck.getEntryLastname().replaceAll("'","''") );
rs = statementLastname.executeQuery();
while (rs.next()) {
Alert alert = new Alert();
alert.setEntryToCheck(entryToCheck);
alert.setAlertStatus(new AlertStatus(new Integer(AlertStatusId.NEW)));
alert.setAlertDate(new Date());
alert.setBlSuspiciousElement(new BlSuspiciousElement(new Integer(rs.getInt("ELEMENT_ID"))));
alert.setMatching(rs.getString("ELEMENT") + " (" + rs.getInt("SCORE") + "%)");
entryToCheck.addAlert(alert);
}
}
}
catch (Exception e) {
e.printStackTrace();
throw e;
}
finally {
DAOUtils.closeConnection(connection, statementLastname);
}
return entries;
}
Really don't know what to look at ...
Thanks !
F
I never used Oracle text tables but my advice is:
Make sure that no one else is executing DDL statements on the table simultaneously.
Also, make sure that, index you have is context index.
Create an index for your column where you want to apply search
........................................
CREATE INDEX "MTU219"."SEARCHFILTER" ON "BL_SUSPICIOUS_ELEMENT " ("LASTNAME")
INDEXTYPE IS "CTXSYS"."CONTEXT" PARAMETERS ('storage CTXSYS.ST_MTED_NORMAL SYNC(ON COMMIT)');
..........................................

how to remove NullExceptionError from Session Variable

I have a varible sem,which takes inputfrom the textbox but if the textbox is kept empty i want it to return "Please Enter a Semester"
int sem;
int parsevalue;
if (int.TryParse(TextBox2.Text, out parsevalue))
{
sem = parsevalue;
Session["Sem"] = sem;
}
else
{
Literal2.Text = "Please Enter a Semester";
}
But If the Textbox is empty the Session["Sem"] returns NullExceptionError in the .aspx file where i have used it.
I searched for the proper conversion using tryparse but could not understand it clearly as to how to print the above mentioned error message.
please help
Thank you in advance
The problem here is that you're assigning the Session variable only when there is a correct value, but you're always trying to access it. This will fail if the value is incorrect (and the Session variable is not set).
Here's your corrected code:
int sem;
int parsevalue;
if (int.TryParse(TextBox2.Text, out parsevalue))
{
sem = parsevalue;
}
else
{
Literal2.Text = "Please Enter a Semester";
}
//Always set the Session variable when it's used somewhere else
Session["Sem"] = sem;
Try:
HttpContext.Current.Session["Sem"] = sem;
Actually:
Session.Add("Sem", sem);
and
Session["Sem"] = sem;
is a same
Q1 Hi , I have a varible sem,which takes inputfrom the textbox but if the textbox is kept empty i want it to return "Please Enter a Semester"
int sem;
int parsevalue;
var txt = TextBox2.Text
if (!String.IsNullOrEmpty(text) && int.TryParse(text, out parsevalue))
{
sem = parsevalue;
}
else
{
Literal2.Text = "Please Enter a Semester";
}
Session["Sem"] = sem;