Ali Haider
Ali Haider

Reputation: 21

Why is my label field is giving me an error in this c# code

Im kinda new to c# so if somebody please tell me why im getting an error

  private void button2_Click(object sender, EventArgs e)
    {

        lblTaskManager.Text = null;
        RegistryKey objRegistryKey = Registry.CurrentUser.CreateSubKey(
               @"Software\Microsoft\Windows\CurrentVersion\Policies\System");
            try
            {
                if (objRegistryKey.GetValue("DisableTaskMgr") == null)
                    objRegistryKey.SetValue("DisableTaskMgr", "1");
                lblTaskManager.Text = ("Disabled");

            else
                objRegistryKey.DeleteValue("DisableTaskMgr");
                objRegistryKey.Close();
                lblTaskManager.Text = ("Enabled");
            }
            catch
            { }
        }
    }
} 

The error is at ("Disabled"); it suggests that a } is required but adding that does not change anything. And also how can I avoid this error in the future.

Upvotes: 1

Views: 45

Answers (2)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186803

Well,

  1. Put RegistryKey creation into using and drop explict Close().
  2. Add {} after if and else.
  3. Remove () around the strings assigned.
  4. Drop that nightmare try { ... } catch {} (ignore all exceptions thrown) and never ever use such code again.

Something like this:

  using (RegistryKey objRegistryKey = Registry.CurrentUser.CreateSubKey(
           "@Software\Microsoft\Windows\CurrentVersion\Policies\System")) {
    if (objRegistryKey.GetValue("DisableTaskMgr") == null) {
      objRegistryKey.SetValue("DisableTaskMgr", "1");
      lblTaskManager.Text = "Disabled";
    }
    else {
      objRegistryKey.DeleteValue("DisableTaskMgr");
      lblTaskManager.Text = "Enabled";
    }
  }

Upvotes: 0

nabuchodonossor
nabuchodonossor

Reputation: 2060

Use { } correct with if:

            if (objRegistryKey.GetValue("DisableTaskMgr") == null)
            {
                objRegistryKey.SetValue("DisableTaskMgr", "1");
                lblTaskManager.Text = ("Disabled");
            }
            else
            {
                objRegistryKey.DeleteValue("DisableTaskMgr");
                objRegistryKey.Close();
                lblTaskManager.Text = ("Enabled");
            }

The ( ) are not needed but shouldn´t harm your code.

And maybe you should move the objRegistryKey.Close(); to the finally of the try catch.

Upvotes: 2

Related Questions