A
Alan Silver
Hello,
I have code like the following...
foreach (Control ctl in Page.Controls) {
if (ctl.ID.StartsWith("X_")) {
// do stuff
}
}
but this gives a run-time error on the second line of "Object reference
not set to an instance of an object" which confuses me.
Surely the foreach loop should ensure that ctl is always set to an
object?
The ID property is a string, so that shouldn't be causing the problem.
If the control doesn't have an ID (if that's possible), the ID should be
"" and the StartsWith() method should return false.
<pause>
I just found something even more weird!! I changed the code to...
foreach (Control ctl in Page.Controls) {
string ctlId = ctl.ID;
Trace.Warn("ctlId = @" + ctlId + "@");
if (ctlId != "") {
if (ctlId.StartsWith("X_")) { // RUN-TIME ERROR HERE
// do stuff
}
}
}
and it bombed out on the same line, even though the tracing shows that
the ID was "". I don't understand how it *got* to that line when the
previous lines checks if the ID is "". Either I've done something
blindingly stupid here (not unlikely!!), or something very weird is
happening.
So, anyone able to explain to me what's going on here? TIA.
I have code like the following...
foreach (Control ctl in Page.Controls) {
if (ctl.ID.StartsWith("X_")) {
// do stuff
}
}
but this gives a run-time error on the second line of "Object reference
not set to an instance of an object" which confuses me.
Surely the foreach loop should ensure that ctl is always set to an
object?
The ID property is a string, so that shouldn't be causing the problem.
If the control doesn't have an ID (if that's possible), the ID should be
"" and the StartsWith() method should return false.
<pause>
I just found something even more weird!! I changed the code to...
foreach (Control ctl in Page.Controls) {
string ctlId = ctl.ID;
Trace.Warn("ctlId = @" + ctlId + "@");
if (ctlId != "") {
if (ctlId.StartsWith("X_")) { // RUN-TIME ERROR HERE
// do stuff
}
}
}
and it bombed out on the same line, even though the tracing shows that
the ID was "". I don't understand how it *got* to that line when the
previous lines checks if the ID is "". Either I've done something
blindingly stupid here (not unlikely!!), or something very weird is
happening.
So, anyone able to explain to me what's going on here? TIA.