Cool12309
Cool12309

Reputation: 171

How do I change an object in a form's properties using a function?

Let's say you're trying to set a label's text. By doing it, you call a function SetText(labelname, "texthere"). What would the SetText 'header' be?

I'm trying:

private void SetText(object foo, string bar) 

but that doesn't work

edit: I have this:

private void SetText(Control thing, string text)
{
if (this.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
Invoke(d, new object[] { text });
}
else
{
thing.Text = text;
}
}

But it says something about invalid number of parameters. What do I need to change?

Upvotes: 0

Views: 113

Answers (2)

Tommaso Belluzzo
Tommaso Belluzzo

Reputation: 23675

Use Control class instead of Object, as the former defines the base class for controls (components with visual representation) and exposes Text property.

private void SetText(Control control, String text)
{
    control.Text = text;
}

Like this, you don't need to box/cast the Object. Otherwise you should also specify the type of the object as you could pass a TextBox, a Label and so on...

Upvotes: 1

Barry Kaye
Barry Kaye

Reputation: 7761

Probably becuase you're referencing the wrong object, try:

private void SetText(ref object foo, string bar)

Note the ref keyword.

Upvotes: 0

Related Questions