C# Unable To Change Components Of Form From Another Class - c#

Before I start, I'd like to say that I have looked for an answer for this over the internet for quite a while, and unable to come to a solution. I know how to solve this, but it doesn't want to work.
Here's what I know: Assuming that I have a label and another class, if I want to manipulate the label I need to create an instance of the form that has the label, call the method of the new class with the form, and then call the method from within the form class that changes the label. This is what I have.
This is from the form class
private void button1_Click(object sender, EventArgs e)
{
Question steve = new Question(1, 1, "nothing", new string[] {});
steve.Show(new Form1(), "I win");
}
public void ChangeLabel(string s)
{
this.lblTest.Text = s;
}
And this is the Question class
public void Show (Form1 f, string str)
{
f.ChangeLabel(str);
}
Syntax-wise this is correct, and when running the debugger lblTest.Text did equal "I win", but there were no visual changes on the form.
P.S. I am in high school and still learning C#, so if I made any mistakes in my explanation or the code, please point them out. Also, disregard the Question constructor, it's useless right now.
Thanks

No ! you don't need to create new instance of the form.
You must pass the current instance using this keyword:
private void button1_Click(object sender, EventArgs e)
{
Question steve = new Question(1, 1, "nothing", new string[] {});
steve.Show(this, "I win"); //change it
}

Related

How to import a value from another Form in C# [duplicate]

This question already has answers here:
Passing Values from one Form to another Form in a Button click
(4 answers)
Closed 2 years ago.
Okay, I saw a couple of answers to similar questions but nothing was quite right, so I thought I would write down my own problem. I have a couple of Forms that are supposed to be connected.
private void btnAdd_Click(object sender, EventArgs e)
{
AuthorForm authorForm = new AuthorForm();
authorForm.Show();
}
This is the code from the Form2 that opens once I want to create a new list of Authors. With that, the third Form "AuthorForm" pops up and that's where I want to enter a name to add to a listBox that is in Form2. I don't know how to pass the string from the TextBox to the other form.
I'm sorry if this doesn't make much sense. I'm pretty bad at trying to explain what I need but if you have questions, I'll try to explain better.
Hi and welcome to StackOverflow. There are several ways to achieve this but I believe the easiest would be to use a property in your AuthorForm as follows:
// Inside AuthorForm create the following...
public string AuthorName { get; private set; }
Having done that, you can set this property either in text changed, or when the user clicks to commit the entered text, you then read this property from the Form2.
// This goes inside the text changed off your name text box.
this.AuthorName = AuthorTextBox.Text; // Assuming the name of the textox is AuthorTextBox
Inside Form2 you call read the property as follows.
private void btnAdd_Click(object sender, EventArgs e)
{
AuthorForm authorForm = new AuthorForm();
authorForm.ShowDialog();
// Read the entered text from the property
var userInput = authorForm.AuthorName;
}
You can proceed to make use of the text the user entered after this.
If i'm not mistaken you want to change Form2 instance after authorForm.Show(); statment
You can initial public variable for example name in Form2 and then send all the form2 instance to AuthorForm with constructor (use this keyword) , now you can change variable from form2 in authorForm
see :
AuthorForm authorForm = new AuthorForm();
authorForm.Show(this);
AuthorForm :
Form2 form2;
public AuthorForm(Form2 form2)
{
this.form2 = form2;
}
public void DoSomething()
{
form2.name = "test";
}
If I got it right, you want to get values from from AuthorForm.
You can do that by adding a property to the AuthorForm, like that:
public string AuthorName { get; set; }
And use authorForm.ShowDialog() so all the opened forms will freeze until you use the Close() method in the form you opened as a dialog. And then you can continue the form.
For example:
AuthorForm.cs:
public void BtnClose_Click(object sender, EventArgs e)
{
AuthorName = "rom_totach";
Close();
}
MainForm.cs:
public void BtnOpenAuthorForm(object sender, EventArgs e)
{
AuthorForm form = new AuthorForm();
form.ShowDialog();
MessageBox.Show(form.AuthorName);
}
I hope I helped!

Why cant I change the SelectedIndex of a combobox from the perspective of another form?

I'm pretty new to C# programming so please forgive my probably super bad mistakes. I have a combobox in SuperAdventure.cs (cboWeapons) and I cant seem to change it from the level of the second form (InventoryScreen.cs) via the following button:
private void btnEquipWeapon_Click(object sender, EventArgs e)
{
SuperAdventure weapon = new SuperAdventure();
String CurrentWeapon = this.cboCurrentWeapon.GetItemText(this.cboCurrentWeapon.SelectedItem);
weapon.cboWeapons_SelectedItemChange(CurrentWeapon);
}
And here is the cboWeapons_SelectedItemChange method from SuperAdventure.cs:
public void cboWeapons_SelectedItemChange(string weapon)
{
cboWeapons.SelectedIndex = cboWeapons.FindString(weapon);
}
The cboWeapons combobox is data bound but I believe that would not make too much of a difference in this case? Also, I was able to change it using a test button I made in SuperAdventure form by just:
private void btnChange(object sender, EventArgs e)
{
cboWeapons.SelectedIndex = cboWeapons.FindString("Sword");
}
And yes, I am making a silly RPG based on Scott Lilly's tutorial in C# with mostly my own forms classes etc... Hope someone will be able to help! Thanks in advance!
An easy solution (I would not really recommend for big projects) would be like this: First, add a private field in InventoryScreen of the SuperAdventure form type. Then add SuperAdventure type to your constructor of InventoryScreen. This way when you call InventoryScreen you will pass your SuperAdventure handler to the new InventoryScreen and from that handle you can make changes to the original existing SuperAdventure form.
SuperAdventure callingForm;
InventoryScreen(Player player, SuperAdventure callingForm) {
InitializeComponent();
_currentPlayer = player;
this.callingForm = callingForm;
cboCurrentWeapon.DataSource = _currentPlayer.Weapons;
cboCurrentWeapon.DisplayMember = "Name";
}
When you call InventoryScreen just pass this as another parameter like:
InventoryScreen iv = new InventoryScreen(player, this);
Finally, the button in InventoryScreen would change to:
private void btnEquipWeapon_Click(object sender, EventArgs e)
{
String CurrentWeapon = this.cboCurrentWeapon.GetItemText(this.cboCurrentWeapon.SelectedItem);
callingForm.cboWeapons_SelectedItemChange(CurrentWeapon);
}
Form1.ComboBox1.SelectedIndex = me.ComboBox2.SelectedIndex
Thats in vb.net but you can translate and try i think

Passing data between C# forms

I am struggling to pass data between two forms (all I want to do is have a textbox in Form1, and show that textbox value in textbox1, which is located in Form2). How would I go about this, using WPF? Have looked at quite a few solutions, but cannot seem to get any of them at all to work.
For the form in which I'm wanting to display the values (in tbd.Text), here is the code:
namespace test
{
/// <summary>
/// Interaction logic for OptionDisplayWindow.xaml
/// </summary>
public partial class OptionDisplayWindow : Window
{
public OptionDisplayWindow()
{
InitializeComponent();
tbd.Text = "k"; //want to change this value based on "s" in the other form
}
The form in which the text is transferred from (want to display the string):
public void Button1_Click(object sender, RoutedEventArgs e)
{
string s = "testText"
}
I have tried every single other answer on SO (spent the past 6 hours trying) and have had absolutely no luck.
EDIT 2: Using the method listed as the best answer here Send values from one form to another form I've come up with this code for Form1:
private void ttbtn_Click(object sender, RoutedEventArgs e)
{
using (Form2 form2 = new Form2())
{
tbd.Text = form2.TheValue;
}
}
And the code for Form2:
public string TheValue
{
get { return arrayTest.Text; }
}
However, I'm getting the error 'Form 2': type used in a using statement must be implicitly convertible to 'System.IDisposable'.
The code that you put in the sample project (that you provided as a link in the comments) should be in your question. Given that it becomes much easier to understand what you're trying to do and to give you a workable solution.
I would suggest creating a "DataTransferObject" and pass that between each form.
public class Dto
{
public string Text;
}
The code in MainWindow would then look like this:
private void button1_Click(object sender, RoutedEventArgs e)
{
var dto = new Dto();
window2 win2 = new window2();
win2.Dto = dto;
win2.ShowDialog();
textBox1.Text = dto.Text;
}
And the code in window2 would look like this:
public Dto Dto;
private void textBox2_TextChanged(object sender, TextChangedEventArgs e)
{
if (this.Dto != null)
{
this.Dto.Text = textBox2.Text;
}
}
That is one way - out of about a million - of transferring data between forms. An advantage of using a data transfer object is that it begins you on the road of separating your data from your UI, and that is generally a very good thing to do.
Another simple way to pass data between forms is using your application's settings.
Step 1: Create a setting, open the "Project" menu and pick "test Properties..."
this will take you to the settings page, create a setting name it however you want, I named mine "PassString" and make sure it's a string type and the Scope is set to user.
Step 2. Lets set the string setting to your textbox.text property, add these changes to the code:
private void button1_Click(object sender, RoutedEventArgs e)
{
Properties.Settings.Default.PassString = textBox1.Text;
window2 win2 = new window2();
win2.ShowDialog();
}
Step 3. Update the text on your second window Initialization Process.
public OptionDisplayWindow()
{
InitializeComponent();
tbd.Text = Properties.Settings.Default.PassString;
}
P.S. you may have to add a reference to reach your application settings.
using test.Properties;

Visual C#: How to add controls to a form created with code?

I'm new to Visual C# and I'm currently stuck on how to create a new form (with code, not design) and add things (namely labels and textboxes) to this new form. Here's what I have right now:
namespace AccountInfo
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
profileForm profile = new profileForm(); // Make new form
profile.Name = "newProfile";
profile.Text = "Add a new profile";
profile.LabelText = "test";
profile.Show(); // Display form
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
public class profileForm : Form
{
// Controls
Label label1 = new Label();
public profileForm()
{
}
public string LabelText
{
set { label1.Text = value; }
}
private void profileForm_Load(object sender, EventArgs e)
{
}
}
}
When I run this code, I get the default form and I click button1. It brings up a new form, but with nothing on it. I expect a label to show up but it won't. I've tried this multiple different ways (this being my most recent method) and I can't get anything to show up. I've looked around StackOverflow and one other topic came up, but its solution didn't work for me. I'd appreciate any insight into this :) Thanks a ton!
Edit: I've also tried this using the constructor instead. It didn't help.
You're creating a Label object in memory but you're not assigning it to a particular parent control, or setting it's position etc... Google "Dynamically create controls C#" and you'll find a tonne of examples.
You basically need to call the following two lines from somewhere in profileForm.
label1.Location = new Point(25,25);
this.Controls.Add(label1);
As suggested by Dylan, you need to add the Label object to the profileForm in the load event as follows:
this.Controls.Add(label1);
Soon, i was watching a video that answers to this question.
It is complete guide how to add dinamicly controlls with the flow layout.
Here is the video: http://windowsclient.net/learn/video.aspx?v=13245

Reference an ASP control inside a function or class method

How do you reference an asp.net control on your page inside a function or a class.
private void PageLoad(object sender, EventArgs e)
{
//An example control from my page is txtUserName
ChangeText(ref txtUserName, "Hello World");
}
private void ChangeText(ref HtmlGenericControl control, string text)
{
control.InnerText = text;
}
Will this actually change the text of the txtUserName control?
I tried this and is working
private void PageLoad(object sender, EventArgs e)
{
ChangeText(txtUserName, "Hello World");
}
private void ChangeText(TextBox control, string text)
{
control.Text = text;
}
Yes, it should, assuming it's at the appropriate point in the page lifecycle, so that nothing else messes with it afterwards. (I don't know the details of ASP.NET lifecycles.
However, it's worth mentioning that there's absolutely no reason to pass it by reference here. It suggests that you don't fully understand parameter passing in .NET - I suggest you read my article on it - once you understand that (and the reference/value type distinction) all kinds of things may become easier for you.
Of course, if you've already tried the code given in the question and found it didn't work, please give more details. Depending on the type of txtUserName, it could even be that with ref it won't compile, but without ref it will just work.
Unless I'm missing something, all you need to do is this:
private void PageLoad(object sender, EventArgs e)
{
txtUserName.Text = "Hello World";
}

Categories