Your problem is that Header
is an object and not a string. You're comparing the two values as if they are, but because Header is an object you're actually doing a reference comparison, not a value comparison. You need to cast Header
to a string by simply calling .ToString()
on Header
.
var tabToDelete = tabControl.Items.OfType<TabItem>().SingleOrDefault(n => (n.Header as string) == stringValue);
if (tabToDelete != null)
tabControl.Items.Remove(tabToDelete);
If this doesn't solve the problem you can force the control to redraw by calling
tabControl.Refresh();
Update
Credit to Daniel Gimenez for spotting the possible null reference exception. The issue of the Header
being set to a control is not a problem however, as all objects can call ToString()
, the real problem is if the Header
is not set at all, resulting in a null
object.