picture of the visual c# properties tab for buttonDealCard_Clicki wanted to create a single object with a method that returned a random card then use it when the button is clicked.
all code shown acts like it dosent exist, autocomplete and auto suggest arent working anymore.
moving the position of the class, whether it was in the same tab, what was static, this fixed the compile time errors.
public static class Deck {
public static Card DealCard() {
int numberOfCards = 52;
int r = new Random().Next(0, numberOfCards - 1);
return new Card(r);
}
//...
}
private void buttonDealCard_Click(object sender, EventArgs e) {
Card newcard = Deck.DealCard();
MessageBox.Show("newcard");
userListBox.Items.Add(newcard);
...
//(working code)
}
i expect the output to be a messagebox woth text "newcard" and a random card object to be added to the listbox then working code output.
the actual output is just the working code output.
after a certain point in my attempts to figure out the problem, nothing i typed would auto suggest or autocomplete, error list would be empty, no "do you want to use an older version to avoid build errors" message, but it acted exactly like before i had written any of this code.
Related
I have a very simple program that for some reason has me stumped. I put it down, came back at it again this morning and I'm still stumped. First off, I'm aware this is not an ideal solution. I have two forms: Main and Log. The Main form has a button that adds to List _debugLog when clicked. When btnDebug is clicked, it opens the Log form, passing _debugLog to it. Everything is fine, the timer is setup and runs, everything is normal. The event log.UpdateLog() is triggered every 2.5 seconds to update the Log form with the updated log. However, mainFormLog.Count and _log.Count are always the same and they BOTH increase when btnAdd is clicked on the main form. How does _log have the new _debugLog (mainFormLog) from the tick event?
namespace Tool
{
public partial class Main : Form
{
private List<string> _debugLog = new List<string>();
public Main()
{
InitializeComponent();
}
private void btnAdd_Click(object sender, EventArgs e)
{
_debugLog.Add("message!");
}
private void btnDebug_Click(object sender, EventArgs e)
{
Log log = new Log(_debugLog);
log.Show();
Timer dt = new Timer();
dt.Interval = 2500;
dt.Enabled = true;
dt.Tick += delegate {
log.UpdateLog(_debugLog);
};
}
}
public partial class Log : Form
{
private List<string> _log;
public Log(List<string> log)
{
InitializeComponent();
_log = log;
}
public void UpdateLog(List<string> mainFormLog)
{
if (mainFormLog.Count > _log.Count)
{
MessageBox.Show("Log has been updated!");
}
else
{
MessageBox.Show("Nothing new!" + mainFormLog.Count.ToString() + " / " + _log.Count.ToString());
}
}
}
}
Well, you're passing the reference to the list from Main to Log, so it's actually the same list.
If you want a separate list that gets initialized with the list from Main you can use:
public Log(List<string> log)
{
InitializeComponent();
_log = new List<string>(log);
}
Maybe this helps to understand the difference between variables and references:
For a value type, the value is the information itself. For a reference
type, the value is a reference which may be null or may be a way of
navigating to an object containing the information.
For example, think of a variable as like a piece of paper. It could
have the value "5" or "false" written on it, but it couldn't have my
house... it would have to have directions to my house. Those
directions are the equivalent of a reference. In particular, two
people could have different pieces of paper containing the same
directions to my house - and if one person followed those directions
and painted my house red, then the second person would see that change
too. If they both just had separate pictures of my house on the paper,
then one person colouring their paper wouldn't change the other
person's paper at all.
All your variables _debugLog, mainFormLog, and _log are pointing to the same list in memory. You've only created one list, and when you assign a new variable to that list, it's just a pointer to some location in memory, it doesn't automatically create a new copy of the list.
I have been googling for the last few days but without a result.
I have a Form called MainForm, i placed four user controls on it.
These user controls contain labels and buttons. Now i created a file called Language.cs
In this file i want to change the languages for all labels when a button is pressed in one of my user controls.
When i coded this in ucSettings.cs i would do it like:
this.label1.Text = res_man.GetString("label_text", cul);
But this doesnt work, beccause my Resourcemanager and my Culture info are both in another file.
So i have
MainForm contains four user controls
The user controls are called, ucAnimalInfo, ucAnimalInput, ucSettings and ucMenuStrip
I have a button in ucSettings that would have to change the language
The text should be set in the file Language.cs
As you can see i change the culture info when a language is selected in a ComboBox:
private void Settings_Language_Cbox_SelectedIndexChanged(object sender, EventArgs e)
{
string SelectedIndex = Settings_Language_Cbox.SelectedItem.ToString();
switch (SelectedIndex)
{
case "English(English)":
ci = CultureInfo.CreateSpecificCulture("en-US");
LanguageSelection = 5;
break;
case "Nederlands(Dutch)":
ci = CultureInfo.CreateSpecificCulture("nl-NL");
LanguageSelection = 6;
break;
}
Now i would like to do something like:
private void Settings_Save_Btn_Click(object sender, EventArgs e)
{
Language.Change();
}
So that it calls my Change method in Language.cs and change a the labels to the correct language. But now i am not able to acces any of the labels in Language.cs even tho they are on public, also my Language.cs file isnt able to get the Resourcemanager and CultureInfo from ucSettings.cs. So my question is, wat is the best way to handle this? I tried using a get/set method but this didn't work out at all, now i am not sure if it is because i messed this up or not.
Edit: I got close by doing it like:
ucSettings.cs
private void Settings_Save_Btn_Click(object sender, EventArgs e)
{
Settings_Language_Cbox.SelectedIndex = LanguageSelection;
BusinessClasses.Language language = new BusinessClasses.Language();
language.setLanguage();
}
Language.cs:
public class Language
{
public MainForm mainform;
public ucAnimalInfo animalinfo;
public ucAnimalInput animalinput;
public ucSettings settings;
public void setLanguage()
{
mainform.Animal_Info_Tab.Info_Id_Text.Text = mainform.Settings_Tab.rs.GetString("Info_Save_Btn", mainform.Settings_Tab.ci);
}
it still gives a NullReferenceException so it not really working, but the closest i got so far. rs and ci are the resourcemanager and cultureinfo
Your question is not very clear, you say user controllers but mean? user control...
As you are new to Windows Mobile/Compact Framework you should start with a simple project first and then evolute to what you want, using small steps.
A good starting for language resource localization maybe at http://www.codeproject.com/Articles/28234/Survival-guide-to-do-resource-localization-using-C.
Use that and then extend with a simple user control and so on.
Then also read http://www.codeproject.com/Articles/16091/User-Interface-Localization-with-the-Compact-Frame about changing the languge 'on-the-fly'.
Please just supply your idea / need (I want to allow this and show that) if you need further assistance.
I have a class Viewer that creates two linked FastColoredTextBoxes. I want the two boxes to scroll together horizontally. I have this code:
public class Viewer : Panel
{
public FastColoredTextBox HeaderRow = new FastColoredTextBox();
public FastColoredTextBox Editor = new FastColoredTextBox();
public Viewer(int _Top, int _Left, int _Height, int _Width, bool _HasHeaderRow, Control control)
{
this.Editor.Scroll += new ScrollEventHandler(Editor_Scroll);
}
void Editor_Scroll(object sender, ScrollEventArgs e)
{
if (e.ScrollOrientation == ScrollOrientation.HorizontalScroll)
{
this.HeaderRow.HorizontalScroll.Value = this.Editor.HorizontalScroll.Value;
}
this.HeaderRow.UpdateScrollbars();
}
}
It doesn't work. I've never tried to do attach events to controls in a class instance before. If I declare the controls in my form and attach a very similar event (minus the .this's) it works fine. Thank you.
i think that for the next time try to tell yourself " what could it be?" and maybe debug a little, like a breackpoint for example. as you probably understood, you had a little mistake in the line
this.HeaderRow.HorizontalScroll.Value = this.HeaderRow.HorizontalScroll.Value;
you meant to write
HeaderRow.HorizontalScroll.Value = Editor.HorizontalScroll.Value;
you just got mixed between the two or something, which happens to all of us. but the first thing i would do is to think and debug it, check the values and let someone look at it. only then post it here.
public static class clsCounter
{
static int count;
public static int Counter
{
get { return count; }
set { count = value; }
}
}
The above is the static class that is used to record a number.
Also, I have two projects within a VS2010 solution, one of which is a class library. In one of these classes, I have got the following code which uses clsCounter.
if (clsCounter.Counter == 0)
countIES++;
else
countIES = 0;
Now, in the other project, I set some new values to clsCounter
clsCounter.Counter = 50;
However, for some reason, I am not able to set clsCounter.Counter to 50, thus I always get countIES++. The code looks okay to me, and I have no idea what's wrong with it? Can anyone help?
Thanks.
EDIT:
I wonder if it has something to do with the scope of projects within vs solution?
Solution Structure
Solution
ExcelAddIn
Form1.cs => (clsCounter.Counter = 50)
...
ClassLibrary
clsCounter => (static class)
...
EDIT 2:
clsCounter.Counter = 50; is actually running in backgroundworker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) event. Could this be a possible issue?
EDIT 3:
I have uploaded a sample project that seems to be able to reproduce the same problem. Here's the shared link: => http://www.4shared.com/folder/sInyNWyi/_online.html
What I would like to do here is to populate a cell with value, Other case after the button 'set value' is pressed. The static class and UDF can be found in the class library.
Note that, to be able to use =testFunc() within excel addin, need to find it in automation server list and enable it. So just go File->Option->Addin->Under Manage Add-in->Click GO->Automation->Ebale ClassLibrary1.UDF
Please also check if the option "Register for COM interop" has been enabled or not before launching the debugger. To find it, go ClassLibrary1 Property -> Build -> Under Output, check Register for COM interop.
Add the following line to your static property:
public static class clsCounter
{
private static int count;
public static int Counter
{
get {
Debug.WriteLine("Counter viewed");
return count;
}
set {
Debug.WriteLine("Counter Changed from {0} to {1}", count, value);
count = value;
}
}
}
Then you can watch your debugger and set breakpoints on the counter which will allow you to find out which part of the code is modifying your counter inappropriately. A static counter will be initialised "at some time" before it is accessed. I would say you are setting the counter and something somewhere is immediately incrementing it before you read it.
Finally, I think I found a workaround although it had nothing to do with the static. I was kinda inspired by the idea of using cookies in the web apps.
Similarly, all I need to do here is:
store a value in a temporary text file, by doing
System.IO.File.WriteAllText(#"C:\countIESValue.txt", value);
in the "set value" button click event handler.
And read the stored value whenever I need it from the above text file and assign it to a local variable.
if(System.IO.File.Exists(#"C:\countIESValue.txt"))
{
string val = System.IO.File.ReadAllText(#"C:\countIESValue.txt");
}
The text file can also be deleted after done processing. In this way, I don't have to worry about any scope or application domain issues, although the permission of writing files is required. I am glad it worked pretty all right for me.
I'm making a simple Guess-The-Number game with a GUI. I need to wait on a loop waiting for the user to input a number in a text box and press "OK". How do I wait for an event inside a loop?
Note: I don't want message boxes. This is done in the main window, hence the need to wait for input.
EDIT: I should have explained myself better. I know that there's a loop inside the GUI. What I want is another loop inside a method. Maybe there's a better way to do this. I could code stuff inside the button's event handler, now that I think about it. Although I'd need global variables. Whataver, I'll think about it, but I hope my question is clearer now.
EDIT 2: Sorry that my question wasn't clear and the edit didn't do much help. First of all, the code is too big to be posted here. I'd probably have to post a screenshot of the GUI, so it wouldn't be of much use. Basically, I have two fields, "Max number" and "Number of allowed guesses". The user enters these two and clicks "Play". A new panel becomes available, with a text box and a "Guess" button. The user enters a guess, and the program checks to see if it's correct.
The purpose of the second infinite loop is to avoid global variables. See, each time the user clicks "Play", the game has to generate a new random number as the correct guess. If everything is done inside a method, no problem. But if the "Guess" button's event handler is called multiple times, the number has to be stored as an instance variable of the Form. Sure, it's not big deal, but I think the number should be a property of the method directing the current game, not of the Form.
I'd also have to keep track of the remaining number of guesses outside of the method. Again, it's no big deal. I just want to avoid globals if I can.
Again, I'm sorry that my question wasn't too clear. I'm kind of tired, and I didn't feel like writing too much. If this still isn't clear, then don't bother. I'll think of something.
C# automatically loops infinitely waiting for events until your form is closed. You just need to respond to the button click event.
Jason Down's suggestion is wise, create a new GuessingGame class and add it to your project. I know you're worried about "global variables" (which everyone is taught in school never to use unless you absolutely have to), but think about your design specifications for a minute.
But if the "Guess" button's event handler is called multiple times, the number has to be stored as an instance variable of the Form. Sure, it's not big deal, but I think the number should be a property of the method directing the current game, not of the Form.
As an alternative, store an instance of your GuessingGame class in the form. This is not a global variable! You said so yourself, the point of the game is keep track of the guesses and generate new numbers to guess every time "Play" is clicked. If you store an instance of the game in the form then open another form (e.g. a Help or About box), then the game's instance would not be available (thus, not global).
The GuessingGame object is going to look something like:
public class GuessingGame
{
private static Random _RNG = new Random();
private bool _GameRunning;
private bool _GameWon;
private int _Number;
private int _GuessesRemaining;
public int GuessesRemaining
{
get { return _GuessesRemaining; }
}
public bool GameEnded
{
get { return !_GameRunning; }
}
public bool GameWon
{
get { return _GameWon; }
}
public GuessingGame()
{
_GameRunning = false;
_GameWon = false;
}
public void StartNewGame(int numberOfGuesses, int max)
{
if (max <= 0)
throw new ArgumentOutOfRangeException("max", "Must be > 0");
if (max == int.MaxValue)
_Number = _RNG.Next();
else
_Number = _RNG.Next(0, max + 1);
_GuessesRemaining = numberOfGuesses;
_GameRunning = true;
}
public bool MakeGuess(int guess)
{
if (_GameRunning)
{
_GuessesRemaining--;
if (_GuessesRemaining <= 0)
{
_GameRunning = false;
_GameWon = false;
return false;
}
if (guess == _Number)
{
_GameWon = true;
return true;
}
else
{
return false;
}
}
else
{
throw new Exception("The game is not running. Call StartNewGame() before making a guess.");
}
}
}
This way, all the data related to the game is encapsulated within the class. Hooking up the events is easy in the codebehind of the form:
GuessingGame game = new GuessingGame();
private void btnPlay_Click(object sender, EventArgs e)
{
int numberOfGuesses = Convert.ToInt32(txtNumberOfGuesses.Text);
int max = Convert.ToInt32(txtMax.Text);
game.StartNewGame(numberOfGuesses, max);
}
private void btnGuess_Click(object sender, EventArgs e)
{
int guess = Convert.ToInt32(txtGuess.Text);
bool correct = game.MakeGuess(guess);
if (correct)
lblWin.Visible = true;
if (game.GameEnded)
{
// disable guess button, show loss label
}
}
You should probably look for a book to actually learn windows programming.
The very basics:
1) There is already an infinite loop deep down in the windows code somewhere. Any windows program is constantly looping and scanning for input.
2) Once input is found, this loop fires off an Event.
3) Your mission, should you choose to accept it, is to write event handlers to handle those events.
you are most likely doing it wrong as it has already been pointed out, but you can use this
Application.DoEvents();
to process events when you are on an actual loop
to do it the right way
- don't use a loop
- use an edit box for the input, then a button
- implement the button onclick event
Yes, and What if I am waiting for Speech events, it could happen anytime event when a function is running, I need to handle that without recursively call a function