Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
hi I'm new with wp8 I'm trying to develop an application . i have some problem to get from my
dictionary i don't know what's wrong here is my code
for (int i = 0; i < SharedInformation.tab.Length; i++)
{
lsCategorie.Clear();
for (int j = 0; j < SharedInformation.SharedLscitation.Count; j++)
{
if (SharedInformation.tab[i].Equals(SharedInformation.SharedLscitation[j].categorie.ToString()))
{
lsCategorie.Add(SharedInformation.SharedLscitation[j]);
}
}
SharedInformation.dic.Add(SharedInformation.tab[i], lsCategorie);
}
and my call
lsCitation = new List<Citation>();
lsCitation = (List<Citation>) SharedInformation.dic["amour"];
listbox.DataContext = lsCitation;
my complete code
public partial class MainPage : PhoneApplicationPage
{
private Popup popup;
private BackgroundWorker backroungWorker;
ShareStatusTask quotesh = new ShareStatusTask();
SmsComposeTask quotesms = new SmsComposeTask();
List<Citation> lsCitation = new List<Citation>();
List<Citation> lsCategorie = new List<Citation>();
// Constructeur
public MainPage()
{
InitializeComponent();
ShowSplash();
}
private void ShowSplash()
{
this.popup = new Popup();
this.popup.Child = new SplashScreen();
this.popup.IsOpen = true;
StartLoadingData();
}
private void StartLoadingData()
{
backroungWorker = new BackgroundWorker();
backroungWorker.DoWork += new DoWorkEventHandler(backroungWorker_DoWork);
backroungWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backroungWorker_RunWorkerCompleted);
backroungWorker.RunWorkerAsync();
}
void backroungWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
this.Dispatcher.BeginInvoke(() =>
{
this.popup.IsOpen = false;
}
);
}
void backroungWorker_DoWork(object sender, DoWorkEventArgs e)
{
//here we can load data
Thread.Sleep(9000);
if (IsolatedStorageSettings.ApplicationSettings.Contains("data") == false)
{
InitializeComponent();
WebClient web = new WebClient();
web.DownloadStringCompleted += web_DownloadStringCompleted;
string uri = "http://quotesconsommation.azurewebsites.net/json/json.php";
web.DownloadStringAsync(new Uri(uri));
IsolatedStorageSettings.ApplicationSettings["data"] = 1;
IsolatedStorageSettings.ApplicationSettings["citation"] = lsCitation;
SharedInformation.SharedLscitation = lsCitation;
MessageBox.Show("" + NetworkInterface.GetIsNetworkAvailable() + "");
}
else
{
SharedInformation.SharedLscitation = IsolatedStorageSettings.ApplicationSettings["citation"] as List<Citation>;
}
for (int i = 0; i < SharedInformation.tab.Length; i++)
{
lsCategorie.Clear();
for (int j = 0; j < SharedInformation.SharedLscitation.Count; j++)
{
if (SharedInformation.tab[i].Equals(SharedInformation.SharedLscitation[j].categorie.ToString()))
{
lsCategorie.Add(SharedInformation.SharedLscitation[j]);
}
}
SharedInformation.dic.Add(SharedInformation.tab[i], lsCategorie);
}
}
void web_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
var rootObject = JsonConvert.DeserializeObject<RootObject>(e.Result);
foreach (var blog in rootObject.citation)
{
lsCitation.Add(blog);
}
and where i'm making the call
List<Citation> lsCitation;
public TOUTES()
{
InitializeComponent();
lsCitation = new List<Citation>();
lsCitation = (List<Citation>) SharedInformation.dic["amour"];
listbox.DataContext = lsCitation;
}
mu sharedinformation class
public static class SharedInformation
{
public static Citation Sharedcitation;
public static List<Citation> SharedLscitation;
public static Dictionary<string, List<Citation>> dic = new Dictionary<string, List<Citation>>();
public static String[] tab = { "amour", "art et spectacle", "arts et creation", "bonheur", "cinema", "cultures", "famille", "fetes", "humour", "insolite", "livres et lettres", "musique", "nature", "philosophie", "pratique", "proverbes", "sagesse", "sciences", "sport et loisirs", "theatre", "travail" };
public static bool connectionstatus;
}
You can't call Clear() on the List<T> - you need to make a new one each time:
for (int i = 0; i < SharedInformation.tab.Length; i++)
{
// Make a new list, don't reuse it!
lsCategorie = new List<object>();
for (int j = 0; j < SharedInformation.SharedLscitation.Count; j++)
{
Since List<T> is a reference type (a class), each time you add, it doesn't add an entire copy of the list - it just adds the reference to the same list. Next time through your loop, you clear out the old list and add new items to it, etc.
As such, the behavior you'll see is that every key will have the items from the last tab's items, since they're all the exact same List<T> instance.
Related
So here is my first file QuizzyService:
List<Question> newQuestions = new List<Question>();
public static List<Question> QuizzyServiceQuestions()
{
using (Stream stream = File.Open("..\\Debug\\questions.bin", FileMode.Open))
{
var binaryFormatter = new BinaryFormatter();
return (List<Question>)binaryFormatter.Deserialize(stream);
}
}
int curQuestion = 0;
public Question NewGame(int questionCount)
{
Random r = new Random();
for(int i = 0; i < questionCount; i++)
{
Question x = QuizzyServiceQuestions()[r.Next(0, QuizzyServiceQuestions().Count)];
while (newQuestions.Contains(x))
{
x = QuizzyServiceQuestions()[r.Next(0, QuizzyServiceQuestions().Count)];
}
newQuestions.Add(x);
}
Console.WriteLine(newQuestions.Count);
return newQuestions[0];
}
public int CheckAnswer(int questionId, int answerId)
{
List<int> IdList = new List<int>();
for (int i = 0; i < QuizzyServiceQuestions().Count; i++)
{
IdList.Add(QuizzyServiceQuestions()[i].Id);
}
return IdList.Single(i => i == questionId);
}
public Question GetNextQuestion()
{
curQuestion += 1;
Console.WriteLine(newQuestions.Count);
//Console.WriteLine(curQuestion);
//Console.WriteLine(this.newQuestions.Count);
return newQuestions[curQuestion];
}
Here the relevant part of the xaml.cs file:
private int totalQuestionCount;
private int currentQuestionCount = 1;
private int correctAnswerCount;
Question newQuestion = new Question();
public MainWindow()
{
InitializeComponent();
}
private void btnNewGame_Click(object sender, RoutedEventArgs e)
{
if (!int.TryParse(tbQuestionCount.Text.Trim(), out totalQuestionCount))
{
tblStatus.Text = "Invalid question count!";
return;
}
correctAnswerCount = 0;
tblStatus.Text = string.Empty;
using(WpfQuizzyClient.QuizzyRef.QuizzyServiceClient client = new WpfQuizzyClient.QuizzyRef.QuizzyServiceClient("WSHttpBinding_IQuizzyService"))
{
newQuestion = client.NewGame(Convert.ToInt32(totalQuestionCount));
UpdateUserInterface(newQuestion);
}
}
private void btnAnswer_Click(object sender, RoutedEventArgs e)
{
Button button = (Button)sender;
int answerId = -1;
switch (button.Name)
{
case "btnAnswerA": answerId = 0; break;
case "btnAnswerB": answerId = 1; break;
case "btnAnswerC": answerId = 2; break;
case "btnAnswerD": answerId = 3; break;
default:
// This should never happen
MessageBox.Show("Invalid button name detected - contact support!");
return;
}
using (WpfQuizzyClient.QuizzyRef.QuizzyServiceClient client = new WpfQuizzyClient.QuizzyRef.QuizzyServiceClient("WSHttpBinding_IQuizzyService"))
{
if (answerId == client.CheckAnswer(newQuestion.Id, answerId))
{
tblStatus.Text = string.Empty;
tblStatus.Text = "Correct! Total: " + currentQuestionCount + " / " + totalQuestionCount;
currentQuestionCount += 1;
UpdateUserInterface(client.GetNextQuestion());
}
else
{
tblStatus.Text = string.Empty;
UpdateUserInterface(client.GetNextQuestion());
}
}
My problem is that when i trigger btnAnswer_Click it doesnt have the list which has been created in NewGame but im not allowed to do something like NextQuestion(Question questionList)
If you need more info just tell me and i'll make sure to provide more as quickly as possible!
i found the fix ... i just had to remove both using and add the "WpfQuizzyClient.QuizzyRef.QuizzyServiceClient client = new WpfQuizzyClient.QuizzyRef.QuizzyServiceClient("WSHttpBinding_IQuizzyService")" before the MainWindow()
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 7 years ago.
Improve this question
When I execute this code in command line, it's working fine:
class Program
{
private static List<Ping> pingers = new List<Ping>();
private static List<string> value = new List<string>();
private static int instances = 0;
private static object #lock = new object();
private static int result = 0;
private static int timeOut = 2500;
private static int ttl = 7;
public static void Main()
{
string baseIP = "192.168.1.";
Console.WriteLine("Pinging destinations of D-class in {0}*", baseIP);
CreatePingers(254);
PingOptions po = new PingOptions(ttl, true);
System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
byte[] data = enc.GetBytes("");
SpinWait wait = new SpinWait();
int cnt =1;
Stopwatch watch = Stopwatch.StartNew();
foreach (Ping p in pingers)
{
lock (#lock)
{
instances += 1;
}
p.SendAsync(string.Concat(baseIP, cnt.ToString()), timeOut, data, po);
cnt += 1;
}
//while (instances > 0)
//{
// wait.SpinOnce();
//}
watch.Stop();
for (int i = 0; i < value.Count; i++)
{
Console.WriteLine(value[i]);
}
DestroyPingers();
Console.WriteLine("Finished in {0}. Found {1} active IP-addresses.", watch.Elapsed.ToString(), result);
Console.ReadKey();
}
public static void Ping_completed(object s, PingCompletedEventArgs e)
{
lock (#lock)
{
instances -= 1;
}
if (e.Reply.Status == IPStatus.Success)
{
string sa = string.Concat("Active IP: ", e.Reply.Address.ToString());
value.Add(sa);
//Console.WriteLine(sa);
String diachiip = e.Reply.Address.ToString();
result += 1;
}
else
{
//Console.WriteLine(String.Concat("Non-active IP: ", e.Reply.Address.ToString()))
}
}
private static void CreatePingers(int cnt)
{
for (int i = 1; i <= cnt; i++)
{
Ping p = new Ping();
p.PingCompleted += Ping_completed;
pingers.Add(p);
}
}
private static void DestroyPingers()
{
foreach (Ping p in pingers)
{
p.PingCompleted -= Ping_completed;
p.Dispose();
}
pingers.Clear();
}
}
But when I convert from it to window form, it doesn't work. I don't kwow why, I have tried many different ways...
Code is here:
public partial class Form1 : Form
{
public static List<Ping> pingers = new List<Ping>();
public static List<string> value = new List<string>();
public static int instances = 0;
public static object #lock = new object();
public static int result = 0;
public int timeout = 2500;
public static int ttl = 7;
public Form1()
{
InitializeComponent();
}
public void btnscan_Click(object sender, EventArgs e)
{
string baseIP = "192.168.1.";
//int kt = Int32.Parse(txtkt.Text);
//int start = Int32.Parse(txtstart.Text);
CreatePingers(254);
PingOptions po = new PingOptions(ttl, true);
System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
byte[] data = enc.GetBytes("");
int cnt = 1;
Stopwatch watch = Stopwatch.StartNew();
foreach (Ping p in pingers)
{
lock (#lock)
{
instances += 1;
}
p.SendAsync(string.Concat(baseIP, cnt.ToString()), timeout, data, po);
cnt += 1;
}
watch.Stop();
//Result alway return 0
lst1.Items.Add(result.ToString());
lst1.Items.Add(value.Count.ToString());
for (int i = 0; i < value.Count; i++)
{
lst1.Items.Add(value[i]);
lst1.Items.Add("\n");
}
DestroyPingers();
string a = "Finished in " + watch.Elapsed.ToString() + ". Found " + result + " active IP-addresses.";
lst1.Items.Add(a);
}
public static void CreatePingers(int kt)
{
for (int start = 1; start <= kt; start++)
{
// class System.Net.NetworkInformation.Ping
Ping p = new Ping();
p.PingCompleted += Ping_completed();
pingers.Add(p);
}
}
public static PingCompletedEventHandler Ping_completed()
{
PingCompletedEventHandler a = new PingCompletedEventHandler(abc);
return a;
}
static void abc(object s, PingCompletedEventArgs e)
{
value.Add("abc");
lock (#lock)
{
instances -= 1;
}
if (e.Reply.Status == IPStatus.Success)
{
string abcd = string.Concat("Active IP: ", e.Reply.Address.ToString());
value.Add(abcd);
result += 1;
}
}
public static void DestroyPingers()
{
foreach (Ping p in pingers)
{
p.PingCompleted -= Ping_completed();
p.Dispose();
}
pingers.Clear();
}
}
What is wrong in this code?
Method SendAsync returns 0 because you are not waiting for it to complete. You are missing await and async (see msdn):
async void btnscan_Click(object sender, EventArgs e)
{
...
await p.SendAsync(string.Concat(baseIP, cnt.ToString()), timeout, data,
...
}
SpinWait was making code to work in console application. In winforms you should not use SpinWait (nor Sleep) in UI thread. You can create another thread (e.g. by using Task) and then you can copy/paste code from console application 1-to-1. But then you will need to use Invoke each time when you want to access UI controls.
async/await is really better.. if it will work (I concluded that from method name, I've no idea what method does, nor how to use it).
Perhaps I miss one thing, if SendAsync returns value, then you can get it by (the requirement to mark method where you use await with async still):
var result = await p.SendAsync(...);
In Quize method I am passing qestions which contains set of all my Questions to be displayed using DisplayQuestion(),Question is my Class, Problem is that I am getting only First Question displayed, how can I get them displayed when i click on listviewItem if suppose questionscontains 10 Questions,than in listviewItem I have displayed numbers(1 2 3 4 5 ....10),when i click on each number how do i display that particular Questiondisplyed on click and if not clicked how all Questions displayed one by one using timer
public partial class GroupExmStart : Form
{
string[] randomQsn = new string[totQsn + 1]; //totQsn is the total number of question for e.g.10
public GroupExmStart(string GroupName, string DurationID)
{
InitializeComponent();
this.GrpID=GroupName;
TopiID=db.GetTopicIDForGroup(GrpID);
string[] conf = db.GetConfiguration(Convert.ToInt16(DurationID)).Split('|');
Question qsn = new Question();
var questions = qsn.Foo(TopiID, conf);
int z = Quiz(questions);
totQsn = Convert.ToInt16(conf[0]);
for (int kk = 1; kk <= totQsn; kk++)
{
ListViewItem lvi = new ListViewItem();
lvi.Text = kk.ToString();
listView1.Items.Add(lvi);
}
randomQsn = new string[totQsn + 1];
timer1.Interval = 1000; //1000ms = 1sec
timer1.Tick += new EventHandler(timer1_Tick);
timer1.Start();
}
int Quiz(List<Question> questions)
{
foreach (Question question in questions)
{
DisplayQuestion(question);
}
return 0;
}
private void DisplayQuestion(Question question)
{
string Q = question.Text;
label5.Text = Q;
string OP1 = question.Option1;
string OP2 = question.Option2;
string OP3 = question.Option3;
string OP4 = question.Option4;
radioButton12.Text = OP1;
radioButton11.Text = OP2;
radioButton10.Text = OP3;
radioButton9.Text = OP4;
}
private void listView1_MouseClick(object sender, MouseEventArgs e)
{
if (randomQsn.GetLength(0) >= 0)
{
if (listView1.SelectedItems.Count > 0)
{
//here how should i get That particular Question so that i can display it
//something like this ? //Convert.ToInt16(listView1.SelectedItems[0].SubItems[0].Text)
DisplayQuestion(question);
}
}
}
private void timer1_Tick(object sender, EventArgs e)
{
tik++;
if (tik == 60)
{
label1.Text = (Convert.ToInt16(label1.Text) - 1).ToString();
tik = 0;
}
}
}
Thanks for any help in advance
The following is what you are looking for. You must grab the text of the list view item and use that as the index of the question.
if (listView1.SelectedItems.Count > 0)
{
var q = Convert.ToInt16(listView1.SelectedItems[0].Text);
var selectedQuestion = questions[q - 1];
DisplayQuestion(selectedQuestion);
}
In order for this to work, modify your constructor to the following:
private List<Question> questions;
public partial class GroupExmStart : Form
{
string[] randomQsn = new string[totQsn + 1]; //totQsn is the total number of question for e.g.10
public GroupExmStart(string GroupName, string DurationID)
{
InitializeComponent();
this.GrpID=GroupName;
TopiID=db.GetTopicIDForGroup(GrpID);
string[] conf = db.GetConfiguration(Convert.ToInt16(DurationID)).Split('|');
Question qsn = new Question();
/// THIS IS MODIFIED //
questions = qsn.Foo(TopiID, conf);
int z = Quiz(questions);
totQsn = Convert.ToInt16(conf[0]);
for (int kk = 1; kk <= totQsn; kk++)
{
ListViewItem lvi = new ListViewItem();
lvi.Text = kk.ToString();
listView1.Items.Add(lvi);
}
randomQsn = new string[totQsn + 1];
timer1.Interval = 1000; //1000ms = 1sec
timer1.Tick += new EventHandler(timer1_Tick);
timer1.Start();
}
I'm trying to declare the array Scores as an array of textboxes. It doesn't have a size. I also need to declare it as an instance variable, and instantiate it in the method, CreateTextBoxes. I keep getting an error, "Scores is a field but is used like a type."
namespace AverageCalculator
{
public partial class AverageCalculator : Form
{
private TextBox[] Scores;
public AverageCalculator()
{
InitializeComponent();
}
private void AverageCalculator_Load(object sender, EventArgs e)
{
btnCalculate.Visible = false;
}
private void btnOK_Click(object sender, EventArgs e)
{
int intNumTextBoxes;
intNumTextBoxes = Convert.ToInt32(txtNumScores.Text);
this.Height = 500;
btnCalculate.Visible = true;
btnOK.Enabled = false;
}
private void CreateTextBoxes(int number)
{
Scores[number] = new Scores[number];
int intTop = 150;
for (int i = 0; i < 150; i++)
{
}
}
}
}
your CreateTextBoxes should probably be something like this:
private void CreateTextBoxes(int number)
{
Scores = new TextBox[number];
for (int i = 0; i < number; i++)
{
Scores[i] = new TextBox();
}
}
As Adil suggested, a List<TextBox> is probably better in this case.
You need to instantiate TextBox but number should be constant You can read more about the array creation expression here. Its better to use List instead of array if you want variable size.
Scores = new TextBox[number];
Using List
List<TextBox> Scores= new List<TextBox>();
Your code should read:
Scores = new TextBox[number];
// do things with this array
The problem is in
private void CreateTextBoxes(int number)
{
Scores[number] = new Scores[number];
int intTop = 150;
for (int i = 0; i < 150; i++)
{
}
}
When you are trying to initialize the array, you are using the name of the field as they type and are including an index to the field name. Just change the new type to TextBox and remove the index accessor like this:
private void CreateTextBoxes(int number)
{
Scores = new TextBox[number];
int intTop = 150;
for (int i = 0; i < 150; i++)
{
}
}
replace line 1 with line 2
Scores[number] = new Scores[number];
Scores[number] = new TextBox();
You can't do this.
Scores[number] = new Scores[number];
Use a list of TextBox.
Problem solved.
The original "private void buttonSave_Click" was changed to:
private void buttonSave_Click(object sender, EventArgs e)
{
if (MusicCollection.FormMain.PublicVars.AlbumList.Count != 100)
{
MusicCollection.FormMain.PublicVars.AlbumList.Add(new Album(NameTextBox.Text));
MessageBox.Show("New Album added: " + NameTextBox.Text);
formMain.ListAlbums(formMain.AlbumsListBox.Items);
this.Close();
}
else
{
MessageBox.Show("No room for new album.");
this.Close();
}
}
Original Post:
I'm new to using C#, so appologies for any seemly obvious mistakes or terrible coding.
I'm trying to create a new Album object (that gets its Name from NameTextBox.Text on Form FormAlbumAC) and add it to List AlbumList when the user clicks the save button on FormAlbumAC. Then I want to list all of AlbumList in a ListBox on Form FormMain.
When I run the program and click the save button, I'm getting the error "ArgumentOutOfRangeException was unhandled, Index was out of range" at the line:
if (MusicCollection.FormMain.PublicVars.AlbumList[i] == null)
// line 8 on my excerpt from Form FormAblumAC
I'm not sure what I'm doing wrong. Any help would be much appreciated, thank you.
Form FormMain:
public const int MAX_ALBUMS = 100;
public int totalAlbums = 0;
public FormMain()
{
InitializeComponent();
}
public static class PublicVars
{
public static List<Album> AlbumList { get; set; }
static PublicVars()
{
AlbumList = new List<Album>(MAX_ALBUMS);
}
}
public ListBox AlbumListBox
{
get
{
return AlbumListBox;
}
}
public void ListAlbums(IList list)
{
list.Clear();
foreach (var album in PublicVars.AlbumList)
{
if (album == null)
continue;
list.Add(album.Name);
}
}
Form FormAlbumAC:
private FormMain formMain;
private void buttonSave_Click(object sender, EventArgs e)
{
int index = -1;
for (int i = 0; i < MusicCollection.FormMain.MAX_ALBUMS; ++i)
{
if (MusicCollection.FormMain.PublicVars.AlbumList[i] == null)
{
index = i;
break;
}
}
if (index != -1)
{
MusicCollection.FormMain.PublicVars.AlbumList[index] = new Album(NameTextBox.Text);
++formMain.totalAlbums;
MessageBox.Show("New Album added: " + NameTextBox.Text);
formMain.ListAlbums(formMain.AlbumsListBox.Items);
this.Close();
}
else
{
MessageBox.Show("No room for new album.");
this.Close();
}
}
Your problem (from your comments) is that your for loop's condition is incorrect. Your for loop is this:
for (int i = 0; i < MusicCollection.FormMain.MAX_ALBUMS; ++i)
There is one problem and one potential problem here. First, when this code is actually run, it's really running:
for (int i = 0; i < 100; ++i)
because MusicCollection.FormMain.MAX_ALBUMS is declared as 100. This causes an error when the length of MusicCollection.FormMain.PublicVars.AlbumList is less than 100, because you're trying to grab an index that doesn't exist.
Instead, you need to iterate from i=0 to the length of ....PublicVars.AlbumList-1, or, preferably, for(int i = 0; i < ....PublicVars.AlbumList.Count; i++).
The second potential problem is that you are potentially skipping index 0. Arrays start at index zero and continue to index length-1. As such, you probably want i++, not ++i. Depends on your implementation, though.