Reputation: 49
I would like to output results from a WMI query to a textbox or label in C#.
But I get a System.FormatException
, when I try to put result into a textbox.text
.
Here is my code:
using System;
using System.Windows.Forms;
using System.Management;
ManagementScope scope = new ManagementScope();
scope = new ManagementScope(@"\\localhost\root\CIMV2");
scope.Connect();
SelectQuery query = new SelectQuery("SELECT * FROM Win32_OperatingSystem");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
using (ManagementObjectCollection queryCollection = searcher.Get())
{
foreach (ManagementObject m in queryCollection)
{
//this line produces the System.FormatException:
textBox.Text = string.Format("Computer Name: { 0}", m["csname"]);
}
}
Upvotes: 1
Views: 1356
Reputation: 37020
The problem with your format string is that you have a space before the 0
in the placeholder: { 0}
. To fix the error, simply remove the space:
textBox.Text = string.Format("Computer Name: {0}", m["csname"]);
You could also simplify the code a little and use string interpolation (a C# 6 feature):
textBox.Text = $"Computer Name: {m["csname"]}";
Upvotes: 2