Reputation: 2393
I'm designing a C# application where I have a groupbox showing OS and RAM related information. I designed it using the controls - labels put together in a Groupbox showing RAM related information.
I have a Refresh button which when clicking should display % of RAM used currently.
For this, I need the label (and also few other labels) inside the groupbox to refresh and re-compute the value.
How do i do this? I tried all below in the RefreshButton_Click event but nothing works:
label1.Refresh();
GroupBox1.Refresh();
Form1.Refresh();
Form1.Invalidate(true);
Panel1.Refresh();
Pls help in this as I do not think reloading an entire form would an efficient solution.
Upvotes: 0
Views: 5992
Reputation: 112682
Create a class containing the properties that you want to display and implement the INotifyPropertyChanged
interface for all of your properties. Then use Data Binding to bind your object to your controls on your form. The controls will update automatically when the properties of your object changes.
See Using the INotifyPropertyChanged functionality or google INotifyPropertyChanged DataBinding WinForms c#.
Upvotes: 1
Reputation: 2797
Easiest, but not too elegant way is to loop all controls in desired group box. Sample code
// Got group box control
Control[] controls = Controls.Find("groupBox1", false);
// List all elements in group box
foreach(var c in ((Control)controls[0]).Controls)
{
// Update in case it is label
if( c.GetType().ToString().EndsWith("Label") )
{
((Label)c).Text = "label...";
}
}
Upvotes: 0
Reputation: 11
In winforms you do not refresh entire forms, use just trigger events that update parts of the forms. I have included below the way of doing this. Basically you need a computational function and you need to update the label by setting the text with the output of that function. You will need to add as many functions as needed.
Ultimatly you will want to create a calculation class since you will want to seperate your UI from your calculations.
Here is an example:
private void RefreshButton_Click(object sender, EventArgs e)
{
//Assuming label1 is for the Ram
label1.text = getRamString();
}
private string getRamString()
{
float ramValue = //Calculate the RAM
return string.Format("{0}%", ramValue);
}
Upvotes: 0
Reputation: 4676
Refreshing won't do anything but display the same assigned value. You must set the new calculated values to your controls inside your RefreshButton_Click handler:
var myNewValue = CalculateNewValue();
label1.Text = myNewValue;
Hope it helps!
Upvotes: 1