Muhammad Hassan Muhammad Hassan - 4 months ago 45
C# Question

Function is inaccessible due to its protection level in C#

I am working on a Windows Form Apps where I have a

TextBox
and I have an event of
textBox1_KeyDown
that triggers a function, that is in another class, that is called after calling its OBJECT and all settings are default. However I am getting the below error as...


Error CS0122 'ClassName.FunctionName(object, KeyEventArgs)' is
inaccessible due to its protection level


Now my Main Form code is something like below...

namespace NewDEMOApps
{
public partial class MainForm : Form
{
ClassName newObj = new ClassName();

public MainForm()
{
InitializeComponent();
}

private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
newObj.FunctionName(sender, e);
}
}
}


And my Class code is something like below...

namespace NewDEMOAppsClass
{
public class ClassName
{
private void FunctionName(object sender, KeyEventArgs e)
{
if (true)
{
if (e.KeyCode.Equals(Keys.Up))
{
MessageBox.Show(UP Key Pressed);
}
if (e.KeyCode.Equals(Keys.Down))
{
MessageBox.Show(DOWN Key Pressed);
}
if (e.KeyCode.Equals(Keys.Enter))
{
MessageBox.Show(Enter Key Pressed);
}
e.Handled = true;
}
}
}
}


Now I want to fix this out via pragmatically not by editing/changing the GUI settings in Visual Studio etc. So, can I do anything to fix this?

Answer

Change the following:

private void FunctionName(object sender, KeyEventArgs e)

to

public void FunctionName(object sender, KeyEventArgs e)

You generally can't access a private method from outside its class. Read here for further information

Comments