Please, you can you help me, how can i change label text in diferent class?
Basic winform script:
public partial class buildEditor : Form
{
public buildEditor()
{
InitializeComponent();
Label maxSkillPoint = new Label();
maxSkillPoint.AutoSize = true;
maxSkillPoint.BackColor = System.Drawing.Color.Transparent;
maxSkillPoint.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(238)));
maxSkillPoint.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(193)))), ((int)(((byte)(196)))), ((int)(((byte)(181)))));
maxSkillPoint.Location = new System.Drawing.Point(528, 687);
maxSkillPoint.Name = "maxSkillPoint";
maxSkillPoint.Text = UniqueValue.spentSkillPoints.ToString();
maxSkillPoint.Size = new System.Drawing.Size(0, 20);
this.Controls.Add(maxSkillPoint);
}
public void maxSkillPoint_TextChanged(Form formInstance, string labelName)
{
// Get reference to the label
var label = formInstance.Controls.Find(labelName, true).FirstOrDefault();
if (null != label && label is Label)
{
(label as Label).Text = "test";
}
}
}
I created next class which will be change text for maxSkill text.
public class ChangeTextForMaxSkill()
{
Button button = new Button();
public ChangeTextForMaxSkill()
{
button.Click += new EventHandler(changeText);
}
private void changeText(object sender, EventArgs e)
{
// Get reference to the label
var buildEditor = new buildEditor();
buildEditor.maxSkillPoint_TextChanged(buildEditor, "maxSkillPoint");
}
}
I really thx for all answers.
I got it very simple:
Hand over the Label control in the constructor of your external class:
using System.Windows.Forms;
public class Yourclass{
private Label UpdateLabel;
public Yourclass (Label yourLabel)
{
this.UpdateLabel = yourlabel;
}
private void action()
{
//here is your update of the label
UpdateLabel.Text = "Your text";
}
}
In the form class, create an instance of "yourclass" and hand over the Label:
Yourclass cls = new Yourclass(Label1);
First of all your naming conventions do not follow standard practices. Both class and method names should use uppercase first letters of words, not camel case as you have done. I have used proper naming conventions in my answer.
You have to pass an instance of your BuildEditor* form to your ChangeTextForMaxSkill.ChangeText() function.
Next, the label object maxSkill is not a property of your BuildEditor class. Therefore, you'd need to actually find a reference to that control within the form since you're dynamically adding it.
public partial class BuildEditor : Form
{
public BuildEditor()
{
InitializeComponent();
Label maxSkill = new Label();
maxSkill.Name = "MaxSkil"; // need the ID to find it later (makes it easier)
maxSkill.Location = new Point(1, 1);
this.Controls.Add(maxSkill);
}
// This is just for testing; assumes you dragged a button from toolbox onto your
// BuildEditor form in the Form Designer
private void button1_Click(object sender, EventArgs e)
{
var changeTextForMaxSkill = new ChangeTextForMaxSkill();
changeTextForMaxSkill.ChangeText(this, "MaxSkil");
}
}
public class ChangeTextForMaxSkill
{
public void ChangeText(Form formInstance, string labelName)
{
// Get reference to the label
var label = formInstance.Controls.Find(labelName, true).FirstOrDefault();
if (null != label && label is Label)
{
(label as Label) .Text = "test";
}
}
}
If you want to test it, just add a button on your form and make the test in the button click handler:
private void button1_Click(object sender, EventArgs e)
{
var changeTextForMaxSkill = new ChangeTextForMaxSkill();
changeTextForMaxSkill.ChangeText(this, "MaxSkil");
}
I've tested and this works :)
Related
I'm trying to changing a user control informations (labels, pictures etc.) from auto added user control. But i cant do it.
Here's my code;
private void KitapButton_Click(object sender, EventArgs e)
{
BıtıkForm BForm = new BıtıkForm();
BForm.kitapGoruntuleme.Visible = true;
}
public partial class BıtıkForm : Form
{
//create controls public instance
public Label label;
public BıtıkForm()
{
InitializeComponent();
//initialize the control
label = new Label();
}
}
Now you can access it from other place like;
BıtıkForm BForm = new BıtıkForm();
BForm.label.Visible = true;
/////// But my Suggestion do not do it like that instead do it like below ///////
BıtıkForm BForm = new BıtıkForm(controlVisible);//Pass the bool value as parameter to the constructor of form
BForm.Show();
And then in form
public partial class BıtıkForm : Form
{
public BıtıkForm(bool controlVisible)
{
InitializeComponent();
//Set Control Visibility
someControl.Visible = controlVisible;
}
}
I didn't use C# too much but It's eventually object oriented. The mistake I made is; I was creating a new instance of 'BıtıkForm' everytime event fired. It could be solved by adding new property where event belongs, and property will carry 'BıtıkForm' object. So It can be managed trough all over the program.
I have labels with footballer's names inside. I want to get footballer's age after clicking on these labels. I do it by this way:
public partial class Form1 : Form
{
Footballer[] team = { /*team initialization*/};
public Form1()
{
InitializeComponent();
}
private void OnLabel_Click(object sender, EventArgs e)
{
for (int i = 0; i < team.Length; i++)
{
if (team[i].Name == this.Text)
{
MessageBox.Show(team[i].Age.ToString());
break;
}
}
}
}
But there is problem. There might be more than one player with the same name. So I want to bind each label with footballer. How can I do this?
For sake of simplicity suppose that you initialize your labels in this mode....
public Form1()
{
InitializeComponent();
int index = 0;
foreach(Label lbl in this.Controls.OfType<Label>())
{
lbl.Text = team[index].Name;
// Make the Tag property reference the Footballer instance
// used to set the label text with the footballer name
lbl.Tag = team[index];
index++;
}
At this point, when you receive the click event, you just need to retrieve the reference from the Tag property and use it directly
private void OnLabel_Click(object sender, EventArgs e)
{
// No loop needed here
Label current = sender as Label;
Footballer player = current.Tag as Footballer;
if(player != null)
MessageBox.Show(player.Age.ToString());
}
}
You should separate out your business logic from your presentation logic. The name is what you presented, but to keep each player/team unique then assign a unique ID.
This is then assigned to the label but hidden from view, so that when the label is clicked the ID is retrieved and you can then do a lookup based on this.
So with Player class like the following:
public class Player
{
public int ID { get;set; }
public string Name { get;set; }
//etc.
}
Then when assigning a Player to label use Label.Tag which is a general purpose field which you can use for anything your want. (Available on all Controls).
label1.Text = MyPlayer.Name;
label1.Tag = MyPlayer.ID;
If I was you, I would also change your Teams to be a List not an array
List<Footballer> team = new List<Footballer>() { /*team initialization*/};
Then you can look up as follows
private void OnLabel_Click(object sender, EventArgs e)
{
Label clickedLabel = (sender as Label);
int id = Convert.ToInt32(clickedLabel.Tag);
Footballer found = team.Find(x => x.Id == id);
MessageBox.Show(found.Age.ToString());
}
I am making an application that loads a separate form, the user puts in information, and then when done, it will show up on the primary form the application loaded with first.
The issue is that I tried multiple solutions to get this to load in, but it will not load in after the information is put in. I have tried this.Controls.Add(Label); which is what I have seen the most, but it has not worked. Another way I tried was doing Label.Show();, but the same result, with nothing showing. The AddContacts(string Name) method below is how I add the contact
The AddContact_Click(object sender, EventArgs e) method is a button that, when pressed, opens another form that allows information to be inserted.
public partial class Phonebook : Form
{
public Phonebook()
{
InitializeComponent();
MaximumSize = new Size(633, 306);
}
private void AddContact_Click(object sender, EventArgs e)
{
MakeContact MC = new MakeContact();
MC.Show();
}
public void AddContacts(string Name)
{
Label name = new Label();
//Added Style and Location of Label...
name.Text = Name;
name.Location = new Point(98, 13);
name.Font = new Font("Microsoft Sans Serif", 13, FontStyle.Bold);
this.Controls.Add(name);
Refresh();
}
}
Below is the Method I used when the Finish button is pressed, for when the user is done with the information, and then the AddContacts() method is called
public partial class MakeContact : Form
{
public MakeContact()
{
InitializeComponent();
MaximumSize = new Size(394, 377);
}
private void FinishContact_Click(object sender, EventArgs e)
{
//FullName is the name of the TextField when asking for a name
string Name = FullName.Text;
Phonebook PB = new Phonebook();
PB.AddContacts(Name);
//Closes Separate Form and goes back to the
Close();
}
}
Expectation:
It should load the label into the form after the information is put in.
Actual:
It will not show what so ever.
EDIT: Added More to the Code and to the Question since I didn't do too good of asking the question, sorry about that :/
An example of what I described in the comments:
When you do this:
Phonebook PB = new Phonebook();
you create a new instance of the PhoneBook class (your form): this is not the same Form instance (the same object) that created the MakeContact Form and the one you're trying to update. It's a different object.
Whatever change you make to this new object, it will not be reflected in the original, existing, one.
How to solve:
Add a Constructor to the MakeContact Form that a accepts an argument of type PhoneBook and a private object of type Phonebook:
private PhoneBook pBook = null;
public MakeContact() : this(null) { }
public MakeContact(PhoneBook phoneBook)
{
InitializeComponent();
this.pBook = phoneBook;
}
Assign the argument passed in the constructor to the private field of the same type. This Field will then used to call Public methods of the PhoneBook class (a Form is a class, similar in behaviour to other class).
It's not the only possible method. You can see other examples here.
Full sample code:
public partial class Phonebook : Form
{
private void AddContact_Click(object sender, EventArgs e)
{
MakeContact MC = new MakeContact(this);
MC.Show();
}
public void AddContacts(string Name)
{
Label name = new Label();
// (...)
this.Controls.Add(name);
}
}
public partial class MakeContact : Form
{
private PhoneBook pBook = null;
public MakeContact() : this(null) { }
public MakeContact(PhoneBook phoneBook)
{
InitializeComponent();
this.pBook = phoneBook;
}
private void FinishContact_Click(object sender, EventArgs e)
{
string Name = FullName.Text;
this.pBook?.AddContacts(Name);
this.Close();
}
}
I try to developp an app for users to create a lot of computer's configuration, with OS / Language / etc ...
When he validate a configuration, I would like the choices to be stored in a custom attribute button
private void VALIDATE_Click(object sender, EventArgs e)
{
string Computer = Text_Computer.Text;
if (myList.Any(str => str.Contains(Computer)))
{
MessageBox.Show(Computer+"Already Exist");
}
else
{
Button button = new Button();
button.Size = new System.Drawing.Size(195, 30);
button.Tag = Computer;
button.Name = Computer;
button.Text = Computer;
button.CustomOS = comboBox_OS.SelectedItem;
button.CustomLanguage = comboBox_Language.SelectedItem;
flowLayoutPanel3.Controls.Add(button);
myList.Add(Computer);
MessageBox.Show(Computer + "added");
}
In my GUI, if Users want to edit a configuration, he click on the new button representing the configuration and all choices are back, like :
comboBox_OS.SelectedItem = button.CustomOS;
comboBox_Language.SelectedItem = button.CustomLanguage;
Is that possible to create my custom attribute like button.CustomOS and button.CustomLanguage ?
Regards
It is possible and quite easy. You just derive a new class from the original Button and declare two new Properties. I included the code into a simple example.
using System;
using System.Windows.Forms;
namespace StackOverflow
{
public partial class FormMain : Form
{
public FormMain()
{
InitializeComponent();
}
private void cbOS_SelectedIndexChanged(object sender, EventArgs e)
{
//Save selection.
ComboBox cb = (ComboBox)(sender);
btn1.CustomOS = cb.SelectedItem.ToString();
}
private void btnSelect_Click(object sender, EventArgs e)
{
//Restore selection on click.
MyButton btn = (MyButton)(sender);
cbOS.SelectedItem = btn.CustomOS;
}
//Declare a new class deriving from the original Button.
public class MyButton : Button
{
public String CustomOS { get; set; }
public String CustomLanguage { get; set; }
}
}
}
In a windows application project I have a form which used a user control. I want to hide a label and textbox on user control. In which event of form I can do this ?
This method in user control which named DoctorPermissionApprove:
public void LoadDoctorPermission(int fromWhere)
{
if (fromWhere == 0) // Başhekimden geldiyse?
{
labelDoctor.Visible = true;
editDoctorWithoutHead.Visible = true;
}
else if (fromWhere == 1) // Normal Hekimden geldiyse
{
labelDoctor.Visible = false;
editDoctorWithoutHead.Visible = false;
}
}
And in form:
private void ExistRequestAndNewEntryForm_Shown(object sender, EventArgs e)
{
var obj = new DoctorPermissionApprove();
obj.LoadDoctorPermission(0);
}
For example I tried in shown event. But it still visible
I want to hide or show this components when the anybody open the form
Thank you a lot
In the UserControl class add a public property to set the internal label visibility true or false. This can be accessed from your parent form where your usercontrol is added.
Example:
public class YourUserControl
{
//This code will be in designer class
private Label lblYourLabelToHide = new Label();
//Create this public property to hide the label
public bool IsLabelVisible
{
set { lblYourLabelToHide.Visible = value; }
}
}
public class YourParentForm
{
//This will be in designer
private YourUserControl userControl = new YourUserControl();
public void Form_Load()
{
//based on some criteria
userControl.IsLabelVisible = false;
}
}