Label is set before string is formatted - c#

So i am creating an x and o's game and i have a label which shows who's turn it is ( WhosTurnLabel) but when i try to format their chosen name into a string it only assigns the string to the label and not the formatted version.
WhosTurnLabel.Text = $"{playerXName}'s Turn";
playerXName is taken from a text box input.
game.playerXName = PlayerXName.Text;
When i am debugging and hover over the $ it shows the string i want the label to be, but when i check the form and hover my mouse over WhosTurnLabel.Text it only shows "'s Turn".
I assign the names to variables in another class then open that form up here:
Game game;
game = new Game();
game.playerXName = PlayerXName.Text;
game.playerOName = PlayerOName.Text;
game.Show();
Thanks in advance for any help.
p.s: im still learning c# and really i need someone to check my programs code, i think there may be a few hiccups

Have you tried passing in the values for playerXName and playerOName as parameters to the Game form constructor? This worked fine for me:
public partial class Game : Form
{
public string playerXName,
playerOName;
public Game(string player1, string player2)
{
InitializeComponent();
playerXName = player1;
playerOName = player2;
WhosTurnLabel.Text = $"{playerXName}'s Turn";
}
}
I just assigned the label text attribute in the constructor, however, playerXName and playerOName are fields in the object and should be accessible to any methods and event handlers within the Game class. Hope this helps!

Looks like the value, at least at the point the string is created is null, empty, or undefined.
Something else to look into, though I am unsure without seeing more of the code, but should
WhosTurnLabel.Text = $"{playerXName}'s Turn";
be
WhosTurnLabel.Text = $"{game.playerXName}'s Turn";
I don't know it would have compiled or not thrown an error in that case, but just something that stood out to me.
But to sum it up, the string is definitely empty or null, at least at the point the string is created.

Add a Game_Shown event and put WhosTurnLabel.Text = $"{playerXName}'s Turn"; in there

Related

How to modify control properties through variable reference

I've been working on making a project of mine more modular. Something I've wanted to do is have multiple buttons use the same function when they perform a similar action, but with different values. I've been stuck on trying to apply this to the following situation:
"When this button is clicked, have the user select an image, and then have a PictureBox display the selected image". Each button has its own PictureBox. All Controls have been created before runtime.
Hope that makes sense!
My last attempt can be seen in the code below- I have tried assigning the Controls(Button and PictureBox) to variables to be stored together in a class. There's 6 of these classes all included within a single List.
I've also tried to store only the Control Names and then using this.Controls.Find to retrieve the Controls.
I've tried quite a few smaller changes such as passing by reference, making the List static, and things such as that would (somehow)magically do the trick- I've gotten desperate.
public class score_control
{
public Button score_button;
public PictureBox score_picture;
public int picture_index;
}
public List<string> score_boxes_names = new List<string>();
public List<score_control> score_boxes = new List<score_control>();
public void add_score_control(Button button, PictureBox pictureBox)
{
score_control new_score = new score_control();
new_score.score_button = button;
new_score.score_picture = pictureBox;
new_score.picture_index = score_boxes.Count();
score_boxes.Add(new_score);
score_boxes_names.Add(button.Name);
}
public score_control find_score_control(string name)
{
int index = score_boxes_names.IndexOf(name);
return score_boxes[index];
}
public frm_settings()
{
InitializeComponent();
add_score_control(btn_score1_image1, pic_score1_image1);
add_score_control(btn_score1_image2, pic_score1_image2);
add_score_control(btn_score1_image3, pic_score1_image3);
add_score_control(btn_score2_image1, pic_score2_image1);
add_score_control(btn_score2_image2, pic_score2_image2);
add_score_control(btn_score2_image3, pic_score2_image3);
}
private void score_button_Click(object sender, EventArgs e)
{
Button image_button = (Button)sender;
if (ofd_png.ShowDialog() == DialogResult.OK)
{
score_control clicked_control = find_score_control(image_button.Name);
score_image[clicked_control.picture_index] = ofd_png.FileName;
clicked_control.score_picture.Image = Image.FromFile(ofd_png.FileName);
}
}
The problem seems centered around this line:
clicked_control.score_picture.Image = Image.FromFile(ofd_png.FileName);
The program throws a NullReferenceException , but clickedcontrol is being recognized in the Local Watch, as well as score_image being noted to be a PictureBox(as it should be).
When I instead held the Control Names in the class, I had broke this line down into multiple lines, but the following line produced a NullReferenceException:
Control[] find_control = this.Controls.Find(clicked_control.score_picture, true);
In this case, clicked_control.score_picture would be a string containing the PictureBox Name. Again, the Local Watch showed that it clicked_control was not null, and neither was score_picture.
Any help figuring out how to properly store a Control within a variable to later be used to modify that Control's properties would be greatly appreciated.
dontpanic was able to help me out with this one. The issue was actually outside of this code - it had to do with the line score_image[clicked_control.picture_index] = ofd_png.FileName;. The way score_image was initialized as an array was incorrect. Fixing that made everything work fine.

Access variable from another form in Visual Studio with c#

I'm using c# and Visual Studio. I want to access a variable from another form. I've found some things like:
textBox1.Text = form22.textBoxt17.Text;
But I don't want to access a textBox value, I just want to access a variable. I've tried this:
string myVar1 = Form2.myVar2;
But that doesn't work.
Any help?
Update
This is what I've got now:
private string _firstName = string.Empty;
public string firstName
{
get
{
return _firstName ;
}
set
{
if (_firstName != value)
_firstName = value;
}
}
In formLogin (where the variable is located), just below public partial class formLogin : Form
Then, later in code, inside button on click event:
OleDbCommand command2 = new OleDbCommand();
command2.Connection = connection;
command2.CommandText = "select firstName from logindb where username = '" + txtUsername.Text + "' and password = '" + txtPassword.Text + "'";
firstName = command2.ExecuteScalar().ToString();
I write this in formAntonyms (from where I want to access the variable) in formLoad event:
formLogin fli = new formLogin();
lblName.Text = fli.firstName;
The problem with all this is that, when formAntonyms opens, lblName is still empty, instead of showing the users name. What am I doing wrong, I've done all the steps right...
You are on the right path, you should not expose controls or variables directly to client code.
Create a read only property in the form/class you want to read the value from:
//Form2.cs
public string MyVar{get{ return textBoxt17.Text;}}
Then, being form22 the instance variable of your already loaded Form2 form class. Then, from any client code that has a reference to it, you can read the value of the property:
string myVal = frm22.MyVar;
EDIT:
Ok based in your last comment, you have a variable in Florm1 and want to access it from Form2, the principle is the same as the previous example, but instead of exposing a control property you now expose a private variable, and instead of living in Form2 it now lives in Form1:
//Form1.cs
private string _myVar = string.Empty
public string MyVar
{
get
{
return _myVar ;
}
set
{
if(_myVar != value)
_myVar = value;
}
}
The property is now read/write so you can update its value from client code
//From From2, assuming you have an instance of Form1 named form1:
string val = form1.MyVar;
...
form1.MyVar = "any";
First of all it is bad object oriented design to access variables from classes directly. It reduces maintainability and reusability.
Your problems arise, because the functionality of your objects is not clear to you.
You should not think in terms of "I want the value of this variable", but in terms of: "Suppose you have a form22, what properties should such a form have?".
Well, apparently it has a size and a position and lots of others, and apparently your form has some information that it displays, and you think that users of this form want to know the text of the displayed information.
Let's suppose the displayed information is named MyInformation. Be aware, that you can only display a description of the information. This descriptive text is not the information itself.
A proper object oriented design of your form would be
class Form22 : Form
{
public string MyInformationText {get {return ...; }
...
}
Now you are communicating to the users of Form22 that a Form22 has some MyInformation. You also communicated that you are not willing to share this information, only to share a descriptive text of the information. Furthermore users of your form can't change this information.
This gives you a lot of advantages. For instance, suppose you don't want to display the text in a TextBox, but in a ComboBox. Or maybe you don't want to display it at all anymore. The users of the form who wanted a descriptive text of MyInformation don't have to change.
Of course your design could be different if you want users of your form to change the information. Probably that would also mean that you need to change the displayed description of your information. But again: users of your form won't need to know this. Again, this gives you the freedom to change it without users having to change:
public MyInformation SpecialInformation
{
get {return this.mySpecialInformation;}
set
{
this.mySpecialInformation = value;
this.UpdateDisplay(mySpecialInformation);
}
}
It depends on your model if you should still provide a property for the displayed text or not: Should all MyInformation object in the world have the same displayed text, or could it be that the displayed text in form22 might differ from the displayed text of MyInformation in form23? The answer to this influences whether MyInformation should have a function to get the descriptive text, or whether the forms should have a function to get the descriptive text.
These are just examples to show that you should think in: what should my object do? What should users of my object be capable to do with my objects. The more you allow them to do, the less you will be able to change. You will have the greatest flexibility if you supply them with no more information than required. Besides you'll need to test much less functionality.

Change Textbox text from another frame(container)

I see here lot of similar question, but I still not find answer that help me in situation.
I have two frame(lets say FrameChild), one is "in" another(practically FrameChild is in this frame, lets say FrameMain).
When I insert all parameters in FrameChild and tap on button witch is on bottom of FrameMain I call method that return string...
Now when i get string i need to change textbox text in FrameChild
I have tray many way.
First idea was something like:
FrameChild frm = new FrameChild;
frm.textbox.text = "somestring";
But nothing happen.
Than i thing use some property.
in FrameChield:
public string setTicNo
{
set
{
textBox.Text = value;
}
}
in FrameMain:
FrameChild frm = new FrameChild;
frm.setTicNo = "somestring";
When i debbuging I get value, but textbox still is empty...
On the end I try to bind textbox text on setTicNo;
public string setTicNo
{
get
{
return setTicNo;
}
set
{
setTicNo = value;
}
}
Xaml:
Text = {Binding setTicNo, Mode=TwoWay,UpdateSourceTrigger=Explicit}
(here i try use more bindings, but every time i get infinite loop.
Please help , I not have more ideas..
Thanx
Did you try building a single view model and bind it to both frames, if it was passed by ref which is the default it will change the value once you do.
A side note implement a INOTIFYPROPERTYCGANGED in the View model

Returned textbox value is empty

Sorry I'm still learning C#, but here's my code and I need help. Basically here's how it is:
The first part of my code went to a settings window where the textbox displays "0%" and my code enters a value of 10 to it.
public void SetDefaultAmount(int amt)
{
Settings.EnterAmt(amt);
}
public void EnterAmt(int amt)
{
string amount = amt.ToString();
Settings.TextBox.Text = amt;
}
So now in setting window, the textbox displays "10%".
My next code goes to a User window where it displays the same textbox and the default value, so the textbox displays "10%" correctly.
I need a code that grabs the textbox value in the Users page, and compare it with the value from the settings page to check if they match. But when i run my code, it gives me the error of "Expected: 10, But was: "string.Empty". How can I fix this? And any better way of streamlining my code? thanks!
This is what my 2nd code is currently, that fails:
**Check if value is 10 (amt = 10)
public void CheckValue(int amt)
{
string amount = amt.ToString();
string actualval = UserPage.GetActualVal();
Assert.AreEqual(amount, actualval, "value did not match");
}
public string GetActualVal()
{
return UserPage.Textbox.Text;
}
It looks like you're comparing amt, an integer, to actualval, a string. Try Assert.AreEqual(amount, actualval).
After another hour of checking my code, it actually works. the problem turned out to be the automation id of the textbox in the Users page, which was changed without my knowledge so i corrected it already. Thanks for checking and i'd just probably try streamline my code.

Calling A Tool From Another Form to Another?

im working on a code-editor(winforms) and Im just wondering if its possible to call a specific box from a form to another?
sample for this set of codes:
int line = 1 + richTextBox1.GetLineFromCharIndex(richTextBox1.GetFirstCharIndexOfCurrentLine());
int column = 1 + richTextBox1.SelectionStart - richTextBox1.GetFirstCharIndexOfCurrentLine();
label1.Text = "line: " + line.ToString() + ", column: " + column.ToString();
***code above was inside a timer which calls the count of line and column in a richtextbox like in lower rightpart of actual code editor .
now im just wondering if its possible to call the label that displays to the main form and will display to another but will still run .
like in mainform theres the code for richtextbox and on other form it should have the code of label that connects to the mainform .
my question is it possible to call a tool function from another form
to another?
hope you could help me, really in need and thanks a lot!
As long as you have a reference to that form toolbox, just expose that Label/TextBox or whatever you want to change via a public property and set it from your context.
public class ToolBox : ToolBoxBase
{
public CustomLabel
{
get
{
return label1.Text;
}
set
{
label1.Text = value;
}
}
}
private ToolBox toolbox;
void ShowToolBox()
{
InitToolBox();
toolbox.CustomLabel = "New label";
}
As I'm not even sure what technology the question refers to I added a poor pseudo example to get you the idea. The InitToolBox method initializes the toolbox and displays it, and sets the field toolbox with a reference to it.
If the other form runs on another thread, then you'll have to invoke the label setter asynchronously. See this question for more instructions.

Categories