|
This is one of the most common problems we get asked, and it's also the one we are least equipped to answer, but you are most equipped to answer yourself.
Let me just explain what the error means: You have tried to use a variable, property, or a method return value but it contains null - which means that there is no instance of a class in the variable.
It's a bit like a pocket: you have a pocket in your shirt, which you use to hold a pen. If you reach into the pocket and find there isn't a pen there, you can't sign your name on a piece of paper - and you will get very funny looks if you try! The empty pocket is giving you a null value (no pen here!) so you can't do anything that you would normally do once you retrieved your pen. Why is it empty? That's the question - it may be that you forgot to pick up your pen when you left the house this morning, or possibly you left the pen in the pocket of yesterdays shirt when you took it off last night.
We can't tell, because we weren't there, and even more importantly, we can't even see your shirt, much less what is in the pocket!
Back to computers, and you have done the same thing, somehow - and we can't see your code, much less run it and find out what contains null when it shouldn't.
But you can - and Visual Studio will help you here. Run your program in the debugger and when it fails, VS will show you the line it found the problem on. You can then start looking at the various parts of it to see what value is null and start looking back through your code to find out why. So put a breakpoint at the beginning of the method containing the error line, and run your program from the start again. This time, VS will stop before the error, and let you examine what is going on by stepping through the code looking at your values. And it's very unlikely for that code to be generating the exception, unless there is something very, very wrong with the data being returned.
So start with the debugger, and verify the exact line that generates the error. If it is that line, then you need to load the returned HTML into a string and have a close look at that. It may be as simple as there is nothing sensible returned because you aren't loading it into a browser that has a valid Agent string, or logged in user...
But we can't do that - we don't have your code, we don't know how to use it if we did have it, we don't have your data. So try it - and see how much information you can find out!
"I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
Dear CodeProject members,
Hope everyone is well, Can someone please help me with a way to get Monitor information as i needed to include in the project i'm working to collect hardware information using C#.
I get the results for one Screen but i would like to get Manufacturer, Model, Serial Number and number of screens as our company have users that have more than 4 screens.
The WMImonitorid has this information and i don't know how to use in this case.
my references are
using System;
using System.Linq;
using System.Management;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Text;
private void WMI_Click(object sender, EventArgs e)
ManagementObjectSearcher objSearcher = null;
ManagementObjectCollection objCollection = null;
ManagementScope objScope = null;
ObjectQuery objQuery = null;
ConnectionOptions objOptions = null;
objOptions = new ConnectionOptions();
objOptions.Impersonation = ImpersonationLevel.Impersonate;
//options.Username = "Username";
//options.Password = "Password";
//options.Authority = "NTLMDOMAIN:GVA.ICRC.Priv";
objScope = new ManagementScope("\\\\Computer\\root\\cimv2:", objOptions);
objScope.Connect();
// Monitor connected to Computer
objQuery = new ObjectQuery("SELECT * FROM Win32_DesktopMonitor");
objSearcher = new ManagementObjectSearcher(objScope, objQuery);
foreach (ManagementObject queryObj in searcher.Get())
{
Console.WriteLine("-----------------------------------");
Console.WriteLine("Win32_DesktopMonitor instance");
Console.WriteLine("-----------------------------------");
Console.WriteLine("Description: {0}", queryObj["Description"]);
}
}
catch (ManagementException e)
{
MessageBox.Show("An error occurred while querying for WMI data: " + e.Message);
}
Thank you and much appreciate your help.
|
|
|
|
|
Win32_DesktopMonitor was deprecated. It also will not tell you accurate information about the displays attached. You may not even get any information at all. On my machine right now, I've got a laptop built-in display and two external monitors. There's only a single instance of Win32_DesktopMonitor being returned and it just lists generic information. There's nothing on the manufacturer or model of the monitors, or anything else that would be useful.
About the only class that returns anything accurate is the Win32_VideoController class, but it won't return any monitor information.
About the only EASILY ACCESSIBLE place I've found that can get you information on the monitors is looking in the registry under HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Enum\DISPLAY. You're looking for the EDID data, which you're going to have to decode to get the vendor/model information.
Be warned. Everything under this key will give you the EDID data for EVERY monitor that has ever been attached to the system. It does NOT remove the data for monitors that are no longer attached!
The hard way to do it would be to call the Windows EnumDisplayDevices function in user32.dll.
|
|
|
|
|
Dear Dave as always your feedback is much appreciated.
Without bothering you would mind doing a small code based on that I could be a base to start.
Much appreciated and wish you a lovely evening
|
|
|
|
|
LOL. No matter which method you choose, none of them is a "small code".
This is going to be a research project. It's probably going to take you a few days.
|
|
|
|
|
I accept the challenge thank you for the help once more😂👍🙏
|
|
|
|
|
Maybe someone can help :) I can’t figure out how to make this code work for borderless Form
Form1
public partial class Form1 : Form
{
clsResize _form_resize;
public Form1()
{
InitializeComponent();
FormBorderStyle = FormBorderStyle.None;
_form_resize = new clsResize(this);
this.Load += _Load;
this.Resize += _Resize;
}
private void _Load(object sender, EventArgs e)
{
_form_resize._get_initial_size();
}
private void _Resize(object sender, EventArgs e)
{
_form_resize._resize();
}
private const int cGrip = 16;
protected override void OnPaint(PaintEventArgs e)
{
Rectangle rc = new Rectangle(ClientSize.Width - cGrip, ClientSize.Height - cGrip, cGrip, cGrip);
ControlPaint.DrawSizeGrip(e.Graphics, BackColor, rc);
}
protected override void WndProc(ref Message m)
{
if (m.Msg == 0x84)
{
Point pos = new Point(m.LParam.ToInt32());
pos = PointToClient(pos);
if (pos.X >= ClientSize.Width - cGrip && pos.Y >= ClientSize.Height - cGrip)
{
m.Result = (IntPtr)17;
return;
}
}
base.WndProc(ref m);
}
clsResize.cs
public class clsResize
{
List<System.Drawing.Rectangle> _arr_control_storage = new List<System.Drawing.Rectangle>();
private bool showRowHeader = false;
public clsResize(Form _form_)
{
form = _form_;
_formSize = _form_.ClientSize;
_fontsize = _form_.Font.Size;
}
private float _fontsize { get; set; }
private System.Drawing.SizeF _formSize {get;set; }
private Form form { get; set; }
public void _get_initial_size()
{
var _controls = _get_all_controls(form);
foreach (Control control in _controls)
{
_arr_control_storage.Add(control.Bounds);
}
}
public void _resize()
{
double _form_ratio_width = (double)form.ClientSize.Width /(double)_formSize.Width;
double _form_ratio_height = (double)form.ClientSize.Height / (double)_formSize.Height;
var _controls = _get_all_controls(form);
int _pos = -1;
foreach (Control control in _controls)
{
_pos += 1;
System.Drawing.Size _controlSize = new System.Drawing.Size((int)(_arr_control_storage[_pos].Width * _form_ratio_width),
(int)(_arr_control_storage[_pos].Height * _form_ratio_height));
System.Drawing.Point _controlposition = new System.Drawing.Point((int)
(_arr_control_storage[_pos].X * _form_ratio_width),(int) (_arr_control_storage[_pos].Y * _form_ratio_height));
control.Bounds = new System.Drawing.Rectangle(_controlposition, _controlSize);
control.Font = new System.Drawing.Font(form.Font.FontFamily,
(float)(((Convert.ToDouble(_fontsize) * _form_ratio_width) / 2) +
((Convert.ToDouble(_fontsize) * _form_ratio_height) / 2)));
}
}
private static IEnumerable<Control> _get_all_controls(Control c)
{
return c.Controls.Cast<Control>().SelectMany(item =>
_get_all_controls(item)).Concat(c.Controls.Cast<Control>()).Where(control =>
control.Name != string.Empty);
}
It works fine when FormBorderStyle.Sizable, but if FormBorderStyle.None get "System ArgumentOutOfRangeException" in this place:
_pos += 1;
System.Drawing.Size _controlSize = new System.Drawing.Size((int)(_arr_control_storage[_pos].Width * _form_ratio_width),
(int)(_arr_control_storage[_pos].Height * _form_ratio_height));
|
|
|
|
|
Start by using the debugger: put a breakpoint on the first line in the function, and run your code through the debugger. Then look at your code, and at your data and work out what should happen manually. Then single step each line checking that what you expected to happen is exactly what did. When it isn't, that's when you have a problem, and you can back-track (or run it again and look more closely) to find out why. You need to find out which argument is out of range, and what the valid range is - until you have that, you can't start looking at why it's out of range!
Sorry, but we can't do that for you - time for you to learn a new (and very, very useful) skill: debugging!
"I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
I do. When im running without border... I don't know how, but this part just skipping
private void _Load(object sender, EventArgs e)
{
_form_resize._get_initial_size();
}
So when they skip, my
var _controls = _get_all_controls(form);
Equally 0. And i get exception
|
|
|
|
|
public void _resize()
{
if (_arr_control_storage.Count == 0) return;
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
"If you just follow the bacon Eddy, wherever it leads you, then you won't have to think about politics." -- Some Bell.
|
|
|
|
|
Wow! That wokrs! Your are my hero! Thanks!
|
|
|
|
|
You're welcome
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
"If you just follow the bacon Eddy, wherever it leads you, then you won't have to think about politics." -- Some Bell.
|
|
|
|
|
Well spotted sir!
Regards,
Rob Philpott.
|
|
|
|
|
Tx
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
"If you just follow the bacon Eddy, wherever it leads you, then you won't have to think about politics." -- Some Bell.
|
|
|
|
|
@User-14042352
If you are trying to "seamlessly" scale a WinForm UI ... and I recommend you don't ... this is an excellent resource: [^].
Remember that most fonts have (internally) special "optical tunings" to look good at certain discrete sizes/weights.
«One day it will have to be officially admitted that what we have christened reality is an even greater illusion than the world of dreams.» Salvador Dali
|
|
|
|
|
hey trying to get my code to dispaly a times table but it just comes out in a straight line
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TestLibary;
namespace ICA25
{
class Program
{
static void Main(string[] args)
{
string sTitle;
bool bExit = false;
sTitle = ("ICA 25 - Times table");
Console.WriteLine("{0,60}\n", sTitle);
do
{
{
int[,] iFinal;
int iNum = GetValue("Please enter the size (4-20) of the times table: ", 4, 20);
Console.Write("Here is the times table for that size: \n");
iFinal = GenerateTT(iNum);
DisplayTT(iFinal);
}
}
while ((YesNo("Would you like to do another? Y or N:") == "Y") && !bExit);
bExit = true;
}
static public int GetValue(string s, int iMin, int iMax)
{
int iNum;
Utilities.GetValue(out iNum, s, 4, 20);
return iNum;
}
static public int[,] GenerateTT(int iValue)
{
int[,] iNum = new int[iValue, iValue];
for (int iRow = 0; iRow < iNum.GetLength(0); iRow++)
{
for (int iCol = 0; iCol < iNum.GetLength(1); iCol++)
{
iNum[iRow, iCol] = (iCol) * (iRow);
}
}
return iNum;
}
static public void DisplayTT(int[,] iFinal)
{
for (int iRow = 0; iRow < iFinal.GetLength(0); iRow++)
{
{
for (int iCol = 0; iCol < iFinal.GetLength(1); iCol++)
{
Console.Write( iFinal[iRow, iCol]);
{
Console.WriteLine();
}
}
}
}
}
static public string YesNo(string sPrompt)
{
string stemp;
do
{
Console.Write("{0}", sPrompt);
stemp = Console.ReadLine().ToString().ToUpper();
if (stemp == "N")
{
Console.Write("Bye");
Console.ReadLine();
}
if (stemp != "Y" && stemp != "N")
{
Console.Write("\nPlease answer Y or N.");
}
}
while ((stemp != "Y") && (stemp != "N"));
return stemp;
}
}
}
|
|
|
|
|
Hi,
1.
the way you set things up, every Console.Write is followed by a Console.WriteLine, so you will never get two adjacent numbers: every number will take a new line.
2.
Writing
Console.Write( iFinal[iRow, iCol]);
{
Console.WriteLine();
}
and writing
Console.WriteLine( iFinal[iRow, iCol]);
is absolutely equivalent.
3.
you fooled yourself by using a lot of redundant brackets. The compiler doesn't mind, but you lost track of what is inside the inner for loop and what isn't.
4.
Once you fix the problem, you'll find out you're not there yet, as Write() or WriteLine() will use whatever number of positions is required to represent the number, so the table may well be badly aligned. If so, start looking at some overloads of int.ToString() .
modified 10-Oct-19 19:33pm.
|
|
|
|
|
Dear CodeProject members,
Hope you can help with the second code that i'm struggling as the other one was answered.
I'm new to C# and compiled this code but I'm stuck and getting error Argument 1: cannot convert from 'System.Management.MamangementScope' to 'string' which is in bold and underlined below
my references are
using System;
using System.Linq;
using System.Management;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Text;
private void WMI_Click(object sender, EventArgs e)
ManagementObjectSearcher objSearcher = null;
ManagementObjectCollection objCollection = null;
ManagementScope objScope = null;
ManagementQuery objQuery = null;
ConnectionOptions objOptions = null;
objOptions = new ConnectionOptions();
objOptions.Impersonation = ImpersonationLevel.Impersonate;
//options.Username = "Username";
//options.Password = "Password";
//options.Authority = "NTLMDOMAIN:DOMAIN";
objScope = new ManagementScope("\\\\Computer\\root\\cimv2:", objOptions);
objScope.Connect();
objQuery = new ObjectQuery("SELECT * FROM Win32_PnPEntity");
objSearcher = new ManagementObjectSearcher(objScope, objQuery);
objCollection = objSearcher.Get();
//objQuery = new ManagementQuery ("SELECT * FROM Win32_PnPEntity");
Thank you and much appreciate your help.
|
|
|
|
|
In your variable declarations, change "ManagementQuery" to "ObjectQuery". You cannot declare an instance variable as an abstract class type and then start calling methods and setting properties on it as the abstract class won't have implementations of those properties and methods.
ManagementObjectSearcher objSearcher = null;
ManagementObjectCollection objCollection = null;
ManagementScope objScope = null;
ObjectQuery objQuery = null;
ConnectionOptions objOptions = null;
modified 9-Oct-19 15:10pm.
|
|
|
|
|
Thank you to all and to Dave thank you for correcting me.
Now i'm very happy to have completed this code.
I thank all of you again for helping.
Wish you a lovely day
|
|
|
|
|
|
I spun a quick project and copy'n'pasted the OP's code into it. Sure enough, he's got the exact error message and the line in comes up on correct.
It took me an embarrassing number of minutes staring at it before I looked up the ManagementObject class and saw it was an abstract. Then it all clicked.
|
|
|
|
|
Hi Dave and Richard, thank you for checking my code.
Richard yes that is error I’m getting and thank you trying Dave.
I’m stuck and will have to check Microsoft links tomorrow at work like I said it is my first time and I’m stuck and don’t understand.
Dave since you tried and saw the errors would you be kind to highlight where I’m going wrong so that I can learn from please but if you think it’s better to read the links then I would do that but if I’m not mistaken I got some of the code from Microsoft to understand and I tried but without success.
Thank you and have a great evening.
|
|
|
|
|
He told you exactly what to do in his original reply!
Did you try it at all?
Sent from my Amstrad PC 1640
Never throw anything away, Griff
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
Thank you Griff, Sorry as I’m new to this forum I apologize I didn’t see the first reply he did and I will try it tomorrow morning 🙏.
Thank you and wish you a lovely evening.
|
|
|
|
|