How do you set the label of a button ?
Here's my code :
private void InitializeMyButton()
{
// Create and initialize a Button.
Button button1 = new Button();
// Set the button to return a value of OK when clicked.
button1.DialogResult = DialogResult.None;
// Add the button to the form.
Controls.Add(button1);
}
Hope someone could find a solution.
CodePudding user response:
Classes that descend from Control
have a Text
property you can set for this, and a Button
is one of those.. Some controls like Button and Label have a Text that isn't set by the user, only the developer. Others (TextBox) are user editable, and you'd read from the Text property to find out what the user has typed into it
Some controls don't really have a sensible use for a Text property (DataGridView, for example) but they descend from Control, so they have one (that isn't used)
In C# a property is like a variable: you set a value for it by putting it on the left hand side of an =
:
label.Text = "Hello";
You can read from them too:
MessageBox.Show("You typed " textbox.Text);
Methods and properties are different; methods "do something"; .Show
above is a method; it shows a MessageBox, and you pass a string into it as an argument, but it's different to a property.
You don't set a property by invoking (running) it - your attempt in the comments button.Text("My button label")
would work if button had a Text method, but Text
on a button is a property, not a method..
When you're looking at C# for the most part you can tell whether something is a property or a method by seeing if there is an open parenthesis (
following it. Methods also have verb names, whereas properties are nouns:
textbox.Clear();
textbox.Text = "hello";
textbox.AppendText("world");
CodePudding user response:
private void InitializeMyButton()
{
// Create and initialize a Button.
Button button1 = new Button();
// Set the button to return a value of OK when clicked.
button1.DialogResult = DialogResult.None;
button1.Text = "OK";
// Add the button to the form.
Controls.Add(button1);
}