How to fix looping issue, even though no loop implemented? - c#

Ok, so I am trying to figure out why I am having a looping issue. The intention of the method GetNewDvdInfo() is to return a new dvd class with 5 properties and will be passed on to DvdController.cs in the CreateDvd() method and will then display all the dvds and the dvd the user added. The problem is that the GetNewDvdInfo() method is repeating itself, but when I was returning null instead, it was not looping.
DvdView.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DvdManager.Models;
/*
GetMenuChoice() : int
GetNewDvdInfo(): Dvd
DisplayDvd(Dvd dvd) : void
EditDvdInfo(Dvd dvd) : Dvd
SearchDvd() : int
ConfirmRemoveDvd(Dvd) : boolean
*/
namespace DvdManager.View
{
public class DvdView
{
public int GetMenuChoice()
{
string input;
int choice;
Console.Clear();
Console.WriteLine("Press 1 to display movies");
Console.WriteLine("Press 2 to add movie");
input = Console.ReadLine();
if (int.TryParse(input, out choice))
{
switch (choice)
{
case 1:
break;
case 2:
break;
default:
Console.WriteLine("Invalid input");
break;
}
}
return choice;
}
public Dvd GetNewDvdInfo() //looping here
{
string inputReleaseYear;
string inputRating;
int id = 4;
string readTitle;
int readReleaseYear;
string readDirector;
float readRating;
Console.WriteLine("What is the Title of the DVD?");
readTitle = Console.ReadLine();
Console.WriteLine("What is the Release Year of the DVD?");
inputReleaseYear = Console.ReadLine();
int.TryParse(inputReleaseYear, out readReleaseYear);
Console.WriteLine("Who is the Director of the DVD?");
readDirector = Console.ReadLine();
Console.WriteLine("What is the star rating of the DVD?");
inputRating = Console.ReadLine();
float.TryParse(inputRating, out readRating);
var dvd = new Dvd(id, readTitle, readReleaseYear, readDirector, readRating);
Dvd newDvd = GetNewDvdInfo();
return dvd;
}
public void DisplayDvd(Dvd dvd)
{
}
public Dvd EditDvdInfo(Dvd dvd)
{
return null;
}
public int SearchDvd()
{
return 0;
}
public Boolean ConfirmRemoveDvd(Dvd dvd)
{
return false;
}
}
}
DvdController.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DvdManager.Models;
using DvdManager.Data;
using DvdManager.View;
/*
Run() : void
Private CreateDvd(): void
Private DisplayDvds(): void
Private SearchDvds(): void
Private EditDvd() : void
Private RemoveDvd() : void
*/
namespace DvdManager.Controllers
{
public class DvdController
{
public DVDList _dvds = new DVDList();
public void Run()
{
Console.WriteLine("Welcome To Dvd Manager");
DvdView view = new DvdView();
var pass = view.GetMenuChoice();
if (pass == 1)
{
CreateDvd();
}
else if (pass == 2)
{
view.GetNewDvdInfo();
CreateDvd();
}
else
Console.WriteLine("Invalid.");
}
private void CreateDvd() //Create
{
var myView = new DvdView();
var dvdInfos = myView.GetNewDvdInfo();
List<Dvd> Dvds = _dvds.GetList();
Dvds.Add(new Dvd(0, "Batman", 2010, "Bruce", 4));
Dvds.Add(new Dvd(1, "Superman", 2009, "John", 4));
Dvds.Add(new Dvd(2, "Wonderwoman", 2012, "Omar", 4));
Dvds.Add(dvdInfos);
DisplayDvds();
}
private void DisplayDvds() //Read List<Dvd> dvds
{
List<Dvd> Dvds = _dvds.GetList();
for (int i = 0; i < Dvds.Count; i++)
{
Console.WriteLine(Dvds[i]);
}
RemoveDvd();
}
private void SearchDvds() //List
{
}
private void EditDvd(int id, Dvd dvd) //Update
{
}
private void RemoveDvd() //Delete int id
{
List<Dvd> Dvds = _dvds.GetList();
//Dvds.RemoveAt(Dvds[1]);
Dvds.Remove(Dvds.Single(x => x.Id == 1));
Console.WriteLine("Removed movie from list:");
for (int i = 0; i < Dvds.Count; i++)
{
Console.WriteLine(Dvds[i]);
}
}
}
}

You are making a recursive call at the end of GetNewDvdInfo(), just remove it.

You are calling this method recursively here:
var dvd = new Dvd(id, readTitle, readReleaseYear, readDirector, readRating);
Dvd newDvd = GetNewDvdInfo(); //!!!
return dvd;
Hence the looping. It seems like this line of code is not needed.

Related

Invoking A Method From Another File C#

I'm having trouble calling my methods. I have 2 separate files. When the user types S then the shake method in my other file will be invoked. So then when the user gets the answer it will be random.
I confused about how to bring that method in another file. Below are both files.
Program.cs:
static void Main(string[] args)
{
Console.WriteLine("Main program!");
Console.WriteLine("Welcome to the Magic 8 Ball");
Console.WriteLine("What would you like to do?");
Console.WriteLine("(S)hake the Ball");
Console.WriteLine("(A)sk a Question");
Console.WriteLine("(G)et the Answer");
Console.WriteLine("(E)xit the Game");
Magic8Ball_Logic.Magic8Ball ball = new Magic8Ball_Logic.Magic8Ball();
string input = Console.ReadLine().ToUpper();
public static string userAnswer = "";
do
{
if (input == "S")
{
if (userAnswer != null)
{
Console.WriteLine("Searching the Mystic Realms(RAM) for the answer");
}
else
{
//Call Method Shake()
}
}
else if (input == "A") {
userAnswer = Console.ReadLine();
}
else if (input == "G") {
//Call Method GetAnswer()
}
} while (input != "E");
}
Magic8Ball.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Magic8Ball_Logic
{
public class Magic8Ball
{
private List<string> _answers;
private int _currentIndex;
private string randomString;
public Magic8Ball()
{
_answers = new List<string>();
_answers.Add("It is certain.");
_answers.Add("It is decidedly so.");
_answers.Add("Without a doubt.");
}
public Magic8Ball(List<string> answers)
{
//I won't use the 20 default. use the ones passed in .
_answers = answers;
}
public void Shake()
{
//picking the index of the answer to show the user
Random r = new Random();
int index = r.Next(_answers.Count);
randomString = _answers[index];
}
public string GetAnswer()
{
//using the index picked by shake to return the answer
//return "";
return randomString;
}
public int AnswerCount
{
get { return _answers.Count; }
}
/* public override string ToString()
{
foreach (var el in _answers)
{
return el;
}
}*/
}
}
First of all you must create an object of this class,then invoke the method.
**Edit**
ball.Shake();
As it was written here: https://stackoverflow.com/a/55986849/10128127
Your Program.cs should be updated like:
replace this comment
//Call Method Shake() with
ball.Shake();
replace this comment
//Call Method GetAnswer() with
ball.GetAnswer();

how to have a comma after each string but not in front

I have a problem with my class where it displays a comma before it displays the string and I cant find a way to take the comma out in the front and keep it in all the other places
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Carnival
{
class Player
{
public string Name { get; set; }
public double SpendingMoney { get; set; }
public string PrizesWon { get; set; }
//constructors
public Player( string n, double sp)
{
Name = n;
SpendingMoney = sp;
PrizesWon = "";
}
//methods
public string Play(GameBooth aGames)
{
string newPrize;
if (SpendingMoney >= aGames.Cost)
{
newPrize = aGames.Start();
//here is what I need to fix
PrizesWon = "," + newPrize + PrizesWon ;
return newPrize;
}
else
{
return "error no money fool";
}
}
}
}
here is the main code if you need it
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Carnival
{
class Program
{
static void Main(string[] args)
{
//local variables
string name;
double money;
int choice = 0;
string newPrize;
//Game objects.
GameBooth balloonDartToss = new GameBooth(2, "tiger plush", "sticker");
GameBooth ringToss = new GameBooth(2, "bear keychain", "pencil");
GameBooth breakAPlate = new GameBooth(1.5, "pig plush", "plastic dinosaur");
Console.ForegroundColor = ConsoleColor.Cyan;
//asking player name
Console.Write("Welcome to the Carnival. What is your name? ");
name = Console.ReadLine();
//asking how much spending money the player has
Console.Write("How much money do you have? ");
money = Convert.ToDouble(Console.ReadLine());
Console.ResetColor();
//Creating player object.
Player Gambler = new Player(name, money);
//main program loop
while (choice != 4)
{
//print menu. Check out the local method below
printMenu();
//retrieve user choice. See the local method below
choice = getChoice();
//main switch. User Choices:
// 1 - we play Baloon Darts Toss and show prize
// 2 - we play ring Toss and show prize
// 3 - we play Break a Plate and show prize
// 4 - Show users all his prizes
switch (choice)
{
case 1:
newPrize = Gambler.Play(balloonDartToss);
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine(newPrize);
break;
case 2:
newPrize = Gambler.Play(ringToss);
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine(newPrize);
break;
case 3:
newPrize = Gambler.Play(breakAPlate);
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine(newPrize);
break;
case 4:
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("{0}, here is your prize list: {1}", Gambler.Name, Gambler.PrizesWon);
Console.ResetColor();
break;
}//end switch
}//end while
//next line simply pauses the program until you hit Enter.
Console.ReadLine();
}//end main
//this method prints the main menu
public static void printMenu()
{
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine();
Console.WriteLine("Select the game you would like to play:");
Console.WriteLine("1. Balloon Dart Toss");
Console.WriteLine("2. Ring Toss");
Console.WriteLine("3. Break a Plate");
Console.WriteLine("4. Get Prizes and Leave Carnival");
Console.Write("Enter Your Choice: ");
Console.ResetColor();
}//end printMenu
//this methods accepts user input 1-4
public static int getChoice()
{
Console.ForegroundColor = ConsoleColor.Yellow;
int input = 0;
do
{
Console.ForegroundColor = ConsoleColor.Yellow;
input = Convert.ToInt32(Console.ReadLine());
if (input < 1 || input > 4)
{
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine("Out of range. Input 1-4 only");
Console.Write("Enter your choice: ");
Console.ResetColor();
}
} while (input < 1 || input > 4);
Console.ResetColor();
return input;
}
}
}
here is my other class if you need that too but you probably don't
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Carnival
{
class GameBooth
{
//properties
public double Cost { get; set; }
public string FirstPrize { get; set; }
public string ConsolationPrize { get; set; }
public int w { get; set; }
public int l { get; set; }
//constructors
public GameBooth(double c, string fp, string cp)
{
Cost = c;
FirstPrize = fp;
ConsolationPrize = cp;
}
//methods
public string Start()
{
Random r = new Random();
w = 1;
l = 1;
for (int i = 1; i < 3; i++)
{
int randomChoice = r.Next(0, 400);
if ( randomChoice == 1)
{
w++;
}
}
if (w == 3)
{
return FirstPrize;
}
else
{
return ConsolationPrize;
}
}
}
}
Update the line to:
PrizesWon = string.IsNullOrEmpty(PrizesWon) ? newPrize : newPrize + "," + PrizesWon;
This uses the conditional operator to return a different result depending on whether or not PrizesWon already has something in it.
In your code you had put (,) before newPrize. For solving this, you have to just put it after PrizesWon variable and it will look like this :
**PrizesWon = newPrize + PrizesWon + ",";**
I hope your problem will be solved by this.

not able to fetch links from pagination using watin dll

Hi i am collecting urls using watin framework. i want to traverse all the pages and collect the link and save it in one text file.I dont know how to add the pagination function.here is my code.
using System.Text;
using System.Threading.Tasks;
using WatiN.Core;
namespace magicbricks
{
class Class1
{
[STAThread]
static void Main(string[] args)
{
IE ie = new IE();
ie.GoTo("http://www.99acres.com/property-in-chennai-ffid?search_type=QS&search_location=HP&lstAcn=HP_R&src=CLUSTER&isvoicesearch=N&keyword_suggest=chennai%20%28all%29%3B&fullSelectedSuggestions=chennai%20%28all%29&strEntityMap=W3sidHlwZSI6ImNpdHkifSx7IjEiOlsiY2hlbm5haSAoYWxsKSIsIkNJVFlfMzIsIFBSRUZFUkVOQ0VfUywgUkVTQ09NX1IiXX1d&texttypedtillsuggestion=chennai&refine_results=Y&Refine_Localities=Refine%20Localities&action=%2Fdo%2Fquicksearch%2Fsearch&suggestion=CITY_32%2C%20PREFERENCE_S%2C%20RESCOM_R");
foreach (var currLink in ie.Links)
{
if (currLink.Url.Contains("b"))
{
Console.WriteLine(currLink.Url);
}
}
Console.ReadLine();
}
}
}
any help will be appreciated.
Here is working solution for that. I changed a bit your code.
using System;
using WatiN.Core;
namespace magicbricks
{
static class Class1
{
private static WatiN.Core.Link _nextPageElement;
private static string _firstPartOfAddress = "";
private static string _lastPartOfAddress = "";
private static int _maxPageCounter = 0;
[STAThread]
static void Main(string[] args)
{
IE ie = SetUpBrowser();
EnterFirstWebpage(ie);
ie.WaitForComplete();
LookFoAllLinks(ie);
for (int i = 2; i < _maxPageCounter; i++)
{
Console.WriteLine("----------------------------Next Page {0}---------------------------", i);
Console.WriteLine(AssembleNextPageWebAddress(i));
EnterNextWebpageUrl(ie,AssembleNextPageWebAddress(i));
LookFoAllLinks(ie);
}
Console.ReadKey();
}
private static IE SetUpBrowser()
{
IE ie = new IE();
return ie;
}
private static void EnterFirstWebpage(IE ie)
{
ie.GoTo("http://www.99acres.com/property-in-chennai-ffid?search_type=QS&search_location=HP&lstAcn=HP_R&src=CLUSTER&isvoicesearch=N&keyword_suggest=chennai%20%28all%29%3B&fullSelectedSuggestions=chennai%20%28all%29&strEntityMap=W3sidHlwZSI6ImNpdHkifSx7IjEiOlsiY2hlbm5haSAoYWxsKSIsIkNJVFlfMzIsIFBSRUZFUkVOQ0VfUywgUkVTQ09NX1IiXX1d&texttypedtillsuggestion=chennai&refine_results=Y&Refine_Localities=Refine%20Localities&action=%2Fdo%2Fquicksearch%2Fsearch&suggestion=CITY_32%2C%20PREFERENCE_S%2C%20RESCOM_R");
}
private static void EnterNextWebpageUrl(IE ie,string url)
{
ie.GoTo(url);
ie.WaitForComplete();
}
private static void LookFoAllLinks(IE ie)
{
int currentpageCounter = 0;
var tmpUrl = string.Empty;
const string nextPageUrl = "http://www.99acres.com/property-in-chennai-ffid-page-";
foreach (var currLink in ie.Links)
{
if (currLink.Url.Contains("b"))
{
Console.WriteLine(currLink.Url);
try
{
if (currLink.Name.Contains("nextbutton"))
{
_nextPageElement = currLink;
}
}
catch (Exception ex)
{
}
try
{
if (currLink.GetAttributeValue("name").Contains("page"))
{
_firstPartOfAddress = currLink.Url.Substring(0, nextPageUrl.Length);
tmpUrl = currLink.Url.Remove(0,nextPageUrl.Length);
_lastPartOfAddress = tmpUrl.Substring(tmpUrl.IndexOf("?"));
tmpUrl = tmpUrl.Substring(0,tmpUrl.IndexOf("?"));
int.TryParse(tmpUrl, out currentpageCounter);
if (currentpageCounter > _maxPageCounter)
{
_maxPageCounter = currentpageCounter;
currentpageCounter = 0;
}
}
}
catch (Exception)
{
}
}
}
}
private static string AssembleNextPageWebAddress(int pageNumber)
{
return _firstPartOfAddress + pageNumber + _lastPartOfAddress;
}
}
}
Some explanation :
variable _maxPageCounter contains max numbers of pages to lookfor links.
We are getting this here :
if (currLink.GetAttributeValue("name").Contains("page"))
{
_firstPartOfAddress = currLink.Url.Substring(0, nextPageUrl.Length);
tmpUrl = currLink.Url.Remove(0,nextPageUrl.Length);
_lastPartOfAddress = tmpUrl.Substring(tmpUrl.IndexOf("?"));
tmpUrl = tmpUrl.Substring(0,tmpUrl.IndexOf("?"));
int.TryParse(tmpUrl, out currentpageCounter);
if (currentpageCounter > _maxPageCounter)
{
_maxPageCounter = currentpageCounter;
currentpageCounter = 0;
}
}
Later we are just looping through pages, by create next address.
private static string AssembleNextPageWebAddress(int pageNumber)
{
return _firstPartOfAddress + pageNumber + _lastPartOfAddress;
}
We could use here as well next button, and click it in loop.
I hope it was helpful.

Lync API: How to send instant message to contact by email address?

I have the email address of a Lync user and want to send him an instant message.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Lync.Model;
using Microsoft.Lync.Model.Conversation;
namespace Build_Server_Lync_Notifier
{
class Program
{
static void Main(string[] args)
{
if (args.Length != 2)
{
Console.WriteLine("Usage: bsln.exe <uri> <message>");
return;
}
LyncClient client = Microsoft.Lync.Model.LyncClient.GetClient();
Contact contact = client.ContactManager.GetContactByUri(args[0]);
Conversation conversation = client.ConversationManager.AddConversation();
conversation.AddParticipant(contact);
Dictionary<InstantMessageContentType, String> messages = new Dictionary<InstantMessageContentType, String>();
messages.Add(InstantMessageContentType.PlainText, args[1]);
InstantMessageModality m = (InstantMessageModality) conversation.Modalities[ModalityTypes.InstantMessage];
m.BeginSendMessage(messages, null, messages);
//Console.Read();
}
}
}
Screenshot
Link to large screenshot: http://i.imgur.com/LMHEF.png
As you can see in this screenshot, my program doesn't really seem to work, even though I'm able to manually search up the contact and send an instant message manually.
I also tried using ContactManager.BeginSearch() instead of ContactManager.GetContactByUri(), but got the same result (you can see in the screenshot): http://pastie.org/private/o9joyzvux4mkhzsjw1pioa
Ok, so I got it working now. Got it in a working state, although I need to do some serious refactoring.
Program.cs
using System;
namespace Build_Server_Lync_Notifier
{
class Program
{
static void Main(string[] args)
{
if (args.Length != 2)
{
Console.WriteLine("Usage: bsln.exe <uri> <message>");
return;
}
LyncManager lm = new LyncManager(args[0], args[1]);
while (!lm.Done)
{
System.Threading.Thread.Sleep(500);
}
}
}
}
LyncManager.cs
using Microsoft.Lync.Model;
using Microsoft.Lync.Model.Conversation;
using System;
using System.Collections.Generic;
namespace Build_Server_Lync_Notifier
{
class LyncManager
{
private string _uri;
private string _message;
private LyncClient _client;
private Conversation _conversation;
private bool _done = false;
public bool Done
{
get { return _done; }
}
public LyncManager(string arg0, string arg1)
{
_uri = arg0;
_message = arg1;
_client = Microsoft.Lync.Model.LyncClient.GetClient();
_client.ContactManager.BeginSearch(
_uri,
SearchProviders.GlobalAddressList,
SearchFields.EmailAddresses,
SearchOptions.ContactsOnly,
2,
BeginSearchCallback,
new object[] { _client.ContactManager, _uri }
);
}
private void BeginSearchCallback(IAsyncResult r)
{
object[] asyncState = (object[]) r.AsyncState;
ContactManager cm = (ContactManager) asyncState[0];
try
{
SearchResults results = cm.EndSearch(r);
if (results.AllResults.Count == 0)
{
Console.WriteLine("No results.");
}
else if (results.AllResults.Count == 1)
{
ContactSubscription srs = cm.CreateSubscription();
Contact contact = results.Contacts[0];
srs.AddContact(contact);
ContactInformationType[] contactInformationTypes = { ContactInformationType.Availability, ContactInformationType.ActivityId };
srs.Subscribe(ContactSubscriptionRefreshRate.High, contactInformationTypes);
_conversation = _client.ConversationManager.AddConversation();
_conversation.AddParticipant(contact);
Dictionary<InstantMessageContentType, String> messages = new Dictionary<InstantMessageContentType, String>();
messages.Add(InstantMessageContentType.PlainText, _message);
InstantMessageModality m = (InstantMessageModality)_conversation.Modalities[ModalityTypes.InstantMessage];
m.BeginSendMessage(messages, BeginSendMessageCallback, messages);
}
else
{
Console.WriteLine("More than one result.");
}
}
catch (SearchException se)
{
Console.WriteLine("Search failed: " + se.Reason.ToString());
}
_client.ContactManager.EndSearch(r);
}
private void BeginSendMessageCallback(IAsyncResult r)
{
_conversation.End();
_done = true;
}
}
}
Try Below Code its working Fine For me
protected void Page_Load(object sender, EventArgs e)
{
SendLyncMessage();
}
private static void SendLyncMessage()
{
string[] targetContactUris = {"sip:xxxx#domain.com"};
LyncClient client = LyncClient.GetClient();
Conversation conv = client.ConversationManager.AddConversation();
foreach (string target in targetContactUris)
{
conv.AddParticipant(client.ContactManager.GetContactByUri(target));
}
InstantMessageModality m = conv.Modalities[ModalityTypes.InstantMessage] as InstantMessageModality;
m.BeginSendMessage("Test Message", null, null);
}

c# quiz project

Please help me with this error! Here ResultValue is an enumeration.
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.
Compiler Error Message: CS0019: Operator '==' cannot be applied to operands of type 'string' and 'Answer.ResultValue'
Source Error:
Line 38: Answer a = (Answer)al[i];
Line 39:
Line 40: if (a.Result == Answer.ResultValue.Correct)
Line 41: correct=correct+1;
Line 42: }
=================================
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class results : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
ArrayList al = (ArrayList)Session["AnswerList"];
if (al == null)
{
Response.Redirect("History.aspx");
}
resultGrid.DataSource = al;
resultGrid.DataBind();
// Save the results into the database.
if (IsPostBack == false)
{
// Calculate score
double questions = al.Count;
double correct = 0.0;
for (int i = 0; i < al.Count; i++)
{
Answer a = (Answer)al[i];
if (a.Result == Answer.ResultValue.Correct)
correct=correct+1;
}
double score = (correct / questions) * 100;
SqlDataSource studentQuizDataSource = new SqlDataSource();
studentQuizDataSource.ConnectionString =
ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
studentQuizDataSource.InsertCommand = "INSERT INTO UserQuiz ([QuizID],
[DateTimeComplete], [Score], [UserName]) VALUES (#QuizID, #DateTimeComplete,
#Score, #UserName)";
studentQuizDataSource.InsertParameters.Add("QuizID",
Session["QuizID"].ToString());
studentQuizDataSource.InsertParameters.Add("Score", score.ToString());
studentQuizDataSource.InsertParameters.Add("UserName", User.Identity.Name);
studentQuizDataSource.InsertParameters.Add("DateTimeComplete",
DateTime.Now.ToString());
int rowsAffected = studentQuizDataSource.Insert();
if (rowsAffected == 0)
{
errorLabel.Text = "There was a problem saving your quiz results into our
database. Therefore, the results from this quiz will
not be displayed on the list on the main menu.";
}
}
}
protected void resultGrid_SelectedIndexChanged(object sender, EventArgs e)
{
SqlDataSource1.FilterExpression = "QuestionOrder=" + resultGrid.SelectedValue;
}
}
code for Answer.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Answer : System.Web.UI.Page
{
private string m_QuestionID;
private string m_CorrectAnswer;
private string m_UserAns;
private string m_Result;
public string QuestionID
{
get
{
return m_QuestionID;
}
set
{
m_QuestionID = value;
}
}
public string CorrectAnswer
{
get
{
return m_CorrectAnswer;
}
set
{
m_CorrectAnswer = value;
}
}
public string UserAns
{
get
{
return m_UserAns;
}
set
{
m_UserAns = value;
}
}
public string Result
{
get
{
if (m_UserAns == m_CorrectAnswer)
{
return "Correct";
}
else
{
return "Incorrect";
}
}
}
public enum ResultValue
{
Correct,
Incorrect
}
}
It's pretty obvious you're trying to compare Enumeration Types with Strings, which aren't the same and can't be compared like that. Instead, I think you should try replacing this bit of code:
public string Result
{
get
{
if (m_UserAns == m_CorrectAnswer)
{
return "Correct";
}
else
{
return "Incorrect";
}
}
}
with
public ResultValue Result
{
get
{
if (m_UserAns == m_CorrectAnswer)
{
return ResultValue.Correct;
}
else
{
return ResultValue.Incorrect;
}
}
}
Try evaluating this :-
if (a.Result == Answer.ResultValue.Correct.ToString())

Categories