我正在编写此应用程序,它可以拉动电池电量并定期向用户显示。我已经将它应用到了控制台应用程序,但是当我将它重新写入Windows窗体时,它使我在使用标签显示值时遇到了一些问题。如何将动态更改的浮动值添加到标签
编辑:我已经包括了变化NIRANJAN卡拉指出,因为我是用多个标签这一点,但它仍然无法正常工作
此外,作为他的要求,我已经加入更多节目布局,以提供一些背景,也许发现错误
这是什么样子:
public partial class Form1 : Form
{
public Form1()
{ InitializeComponent();
// Imagine all the visual stuff going here (icons and menus, etc.)
//I start the thread
batThing = new Thread(new ThreadStart(batThing));
batThing.Start();
}
private void Form1_Load(object sender, EventArgs e)
{
Type power = typeof(PowerStatus);
PropertyInfo[] pi = power.GetProperties();
#region Cargador
//0 = PowerLineStatus --> Charger on or not?
object EdeCargador = pi[0].GetValue(SystemInformation.PowerStatus, null);
//turns charger state into int
int edc = Convert.ToInt32(EdeCargador);
int On = Convert.ToInt32(PowerLineStatus.Online);
On = 1;
int Off = Convert.ToInt32(PowerLineStatus.Offline);
Off = 0;
int Unk = Convert.ToInt32(PowerLineStatus.Unknown);
Unk = 255;
if (edc == On)
{
string CargadorConectado = "-Cargador Conectado-";
label2.Text = CargadorConectado;
string EdeBateria2 = "-Cargando-";
label4.Text = EdeBateria2;
}
else
{
string CargadorDesconectado = "-Cargador Desconectado-";
label2.Text = CargadorDesconectado;
#endregion
#region Cantidad de Bateria
//3 = BatteryLifePercent --> tells the % of bat available
object CantdeBat = pi[3].GetValue(SystemInformation.PowerStatus, null);
//string to float , then * 100 to get a %
float num = (Single.Parse(CantdeBat.ToString())) * 100;
// shows a % and says if battery is full or low
string EdeBateria = num.ToString() + "%";
if (num == 100)
{
EdeBateria = "-Batería Completa-";
label4.Text = EdeBateria;
}
else if (num <= 25)
{
EdeBateria = "-Batería Baja. Conecte el cargador-";
label4.Text = EdeBateria;
}
else if (num > 25 & num < 100)
{
//nada
}
if (num <= 0)
{
EdeBateria = "No tenes bateria gil";
label4.Text = EdeBateria;
}
}
#endregion
#region Tiempo Restante
//4 = BatteryLifeRemaining --> Indicates the remaining battery time
object TdeBat = pi[4].GetValue(SystemInformation.PowerStatus, null);
double tiempobat = (Double.Parse(TdeBat.ToString()));
if (tiempobat == -1)
{
string NoHayBat = "El equipo no está operando a través de una batería";
label5.Text = NoHayBat;
}
else if (tiempobat != -1)
{
//gets time in seconds and turns it into hours , min and secs
TimeSpan t = TimeSpan.FromSeconds(tiempobat);
string TiempoRestante = string.Format("El tiempo de uso restante es de: {0:D1} horas, {1:D2} minutos y {2:D2} segundos",
t.Hours,
t.Minutes,
t.Seconds
);
label5.Text = TiempoRestante ;
}
#endregion
} // fin de form1
编辑:我发现在从一种方法跳转到另一种方法时会遇到一些问题,例如,我原来的问题是“标签4”,我发现这是由于充电器状态的逻辑,所以我增加这样的:
string EdeBateria2 = "-Cargando-";
label4.Text = EdeBateria2;
添加此时,我有充电器连接它显示得这么好后,但是当我断开进入“其他”其中I编码的问题开始对标签4的条件句的充电器。
标签2和标签5中的字符串发生了变化,因为我将充电器从笔记本电脑上断开,没有任何问题,问题在于标签4仍然存在。当我断开充电器时,它会停止显示我定义为'-Cargando-'的信息,并且只显示它的名称'label4'。
我卡住了,有什么想法吗?
我使用C#在VS 2015
你为什么使用多个标签。你应该只使用一个标签..然后用你想要的字符串更新它的文本。 –
你确定所有的标签都在你的代码路径中更新了吗? – Kayani