Cannot explicitly call operator or accessor and static - c#

I have two stupid questions :
The first one :
I have already asked this and I'm truly sorry to ask it again (even more so because there are a lot of posts about it), but now I really don't understand why that happens even if I read every other post, here is my code :
public class PageTitre {
...
public void situation(string s) {
onglet.get_Range("C11").Value = "(" + s + ")";
}
}
public class PPE_Process {
public static PageTitre pageTitre;
public static void MainProcess() {
...
pageTitre = new PageTitre();
...
}
}
public partial class PPE_Ribbon {
private void SituationEditBox_TextChanged(object sender, RibbonControlEventArgs e)
{
PPE_Process.pageTitre.situation(SituationEditBox.Text);
}
}
I have tried some other things, like putting situation as a variable of PageTitre and having a get and a set, and
private void SituationEditBox_TextChanged(object sender, RibbonControlEventArgs e)
{
PPE_Process.pageTitre.set_situation(SituationEditBox.Text);
}
Or
private void SituationEditBox_TextChanged(object sender, RibbonControlEventArgs e)
{
PPE_Process.pageTitre.situation = SituationEditBox.Text;
}
But nothing worked, with the same error: cannot explicitly call operator or accessor.
I guess there is a problem with the static? If that is the case, here is my second question:
Second one :
I read a lot of documentation about it but I really can't understand what is the use of "static"... Is it just so that we can't change the value outside of the class, or something like this? Then, would it really change something if I take off every static there is in my code?
Again, I am sorry that you have to answer this question again and again, but I understand a lot better if that is directly related to my code, and not someone answering someone else about some other random code, which has a different problem than mine. :/
Edit to add more information:
There shouldn't be any problem with .Value or .get_Range, as it works on other parts of the code, but
For .Value, here is the information given by Visual Studio:
void Range.set_Value([object RangeValueDataType = System.Type.Missing], [object value = System.Type.Missing])
For .get_Range: Excel.Range_Worksheet.get_Range(object Cell1, [object Cell2 = System.Type.Missing])
For static, I still don't really understand all these "instances" things, but I will try to look more, and add another question in this forum if I still don't understand after this.

To your first question: I don't see any problem with your call of the method situation, maybe the problem is the statement inside the method (get_Range("C11"))?
To your second question: When you make a variable/property/method static it means that it is independent from any instance (object) of the class. Otherwise you couldn't access the property PPE_Process.pageTitre without an instance of PPE_Process.

Alrighty, I changed nothing in my code but now it works with
private void SituationEditBox_TextChanged(object sender, RibbonControlEventArgs e)
{
PPE_Process.pageTitre.situation = SituationEditBox.Text;
}
So... I don't know, it was maybe a problem with the build of my solution, but that's pretty fortunate :)

Related

SelectedIndex returns -1 in void/static void function

I have a problem with the combobox.SelectedIndex function. The problem is that in void and static void it just returns a -1. Now before anyone comes and says if there is anything in it at all, yes it is, I've debugged the code and found that it only returns a -1 in static void and void , now I'm curious as to why it doesn't work, actually a very simple code.
void writecombo()
{
int CURRENT_LOG = combo.SelectedIndex; //< -1
Globals.LG[CURRENT_LOG] += "Hello!" + Environment.NewLine; //Crash, because it is -1
...
}
Where it works:
private void textbox1_KeyDown(object sender, KeyEventArgs e)
{
if (GetAsyncKeyState(Keys.Enter) < 0)
{
int CURRENT_LOG = combo.SelectedIndex; // Not Null
Globals.LG[CURRENT_LOG] += "Hello!" + Environment.NewLine;
...
}
}
I would be happy to get help and also if someone could explain to me why this is the case :)
EDIT: The problem only comes when I want to access this void from a static void, I wanted to use it to access the objects in form1 in a static. (var from = new Form1)
MRE
void vs static void isn't exactly your problem. It's a static member trying to access the non-static members of its class. That barrier cannot be crossed.
When a member is static, there's only one instance of it, and it's attached to the class; it can only access members of the class that are also marked with the static keyword.
Members that are not marked static can access all the members of the class, including its static members. Each object you create from the class using new essentially gets its own copy of the non-static members.
In your code sample, you're trying to access a non-static member from a static member, and the runtime is telling you that can't be done.
First of all, thanks to everyone tried to help me. It seems like accessing/calling an static function, to access with that the Form1 contents is a complicated and hard thing to do.
So, i found another way, instead trying to call a function, i am going to use a timer to check a global boolean value, if it is true, it should execute the code, very simple, it's not good, but at least a way to deal with it.
Still, i am opend for answers if anyone found a good and easy way to access the contents of a form with a static function in it.

Calling methods assignment fix via confusing instructor comment in C#

So a question on a quiz in my programming class is this: "Create a value returning method called squareThis() independent of but called from the test app. This method cannot refer to any object within the application. Rather, pass the double value dblValue to the method and place the result into lblOutput once btnProblem4 is pressed. Have the method return dblValue squared."
I have established dblValue and called the method in a click event, specifically btn_4. I was not sure what he meant by calling it independently, and created another .cs within the program specifically for this problem. This is the code for the click event.
public void btnProblem4_Click(object sender, EventArgs e)
{
FinalCalc c = new FinalCalc();
lblOutput.Text = c.FinalPiece();
}
This is the separate class form I created in the program:
namespace MethodsQuiz
{
class FinalCalc
{
public string FinalPiece()
{
double Math4 = Math.Pow(1.5, 2);
string mathfinal = Math4.ToString();
return mathfinal;
}
}
}
The instructor marked this question with this comment: "#4 problem? Don't find the method."
This is my first post, so I apologize if this is in a terrible format. I am not asking you to solve this question for me; only to explain the question and the instructors comment, as well as what I have done wrong. Again, I am not seeking you to answer this question, just to provide assistance so that I can understand. Thank you.
Probably he meant having a self static method in the same class (in your control or Forms code behind class) and call that method in your button click event like
private static string FinalPiece(double dblVal)
{
double squared = dblVal * dblVal;
return mathfinal.ToString();
}
public void btnProblem4_Click(object sender, EventArgs e)
{
lblOutput.Text = FinalPiece(10);
}

Call Result of one Class and use it in other Class

It might be easy but im stuck!
i do have a class that Create one Command for me like:
As you can see this Encode will Return me bCommand!
Now im having a Button Function that i should call this bCommand and Assign it as a Value like:
So i got the Error that Bcommand Does not Exist in Current Context
I'm looking for any advice how i can Solve the Problem.
You need to assign the results of the Encode method to a variable.
private void btnModel_Click(object sender, EventArgs e)
{
byte[] bCommand = Encode("C11", "");
WriteData(bCommand); // bCommand will now exist in this context
}

Basic use of user controls, closing a user control and opening another, user control parameters

ladies and gentlemen, once again I unfortunately am going to bother you with newbie stuff. I have searched for this information for hours, so if there’s a thread with what I want on it, it’s buried deeper than I could find.
This was my first question here, and Mark Hall was kind enough to set me straight. Since then, I have created a new project and recreated my first three screens as user controls – a container/login, a choice screen, and a main screen (currently empty). If a user has more than one collection, the choice screen pops up and allows them to choose a collection.
I did run into a snag with parameters, but I’m solving that by overloading the form declaration (solution found here) – yes, I know it’s much better to send parameters through calls, but I’d hate to have to create a call for each parameter (do I?) and… OK, OK, I’m better at this than {get, set}. Man, I hate being a newbie.
Anyways, I’m having trouble with the choice form – I can’t seem to call it, close it, then go to the main form. I have no problem (if there’s only one collection) in going straight to the main form, it’s that darn choice form. Yes, I know I could include a choice datagridview, but a few of our end users aren’t the sharpest bulb in the tool shed, and need hand-holding. Anyways, here’s the code.
CONTAINER/LOGIN SCREEN
namespace DeleteThis
{
public partial class ContainerForm : Form
{
Main Main = new Main();
LoginCollectionChoice LoginChoice = new LoginCollectionChoice();
DataTable dtPermissions = new DataTable();
public ContainerForm()
{
InitializeComponent();
Main.ExitEvent += new Main.ExitEventHandler(Main_ExitEvent);
LoginChoice.ExitEvent += new
LoginCollectionChoice.ExitEventHandler(LoginChoice_ExitEvent);
}
void LoginChoice_ExitEvent(object sender, EventArgs e)
{
pnlcontainer.Controls.Remove(LoginChoice);
}
void Main_ExitEvent(object sender, EventArgs e)
{
pnlcontainer.Controls.Remove(Main);
}
private void btnLogin_Click(object sender, EventArgs e)
{
LoginProcedure();
}
private void LoginProcedure()
{
DataTable dtPermissions = AdminClass.GetCollectionsForUser(int.Parse(txtbxUserName.Text));
if (dtPermissions.Rows.Count == 1)
{
//Valid user, one collection. Head right in.
pnlcontainer.Controls.Add(Main);
Main.BringToFront();
}
else
{
//More than one collection found. Giving user choice
LoginCollectionChoice LoginChoice = new LoginCollectionChoice(dtPermissions);
pnlcontainer.Controls.Add(LoginChoice);
LoginChoice.BringToFront();
}
}
private void btnExitProgram_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
I hope I didn't kill anything in the snipping. And now the choice screen…
public partial class LoginCollectionChoice : UserControl
{
public delegate void ExitEventHandler(object sender, EventArgs e);
public event ExitEventHandler ExitEvent;
private static DataTable dtPermit;
DataTable dtPermissions = new DataTable();
public LoginCollectionChoice()
{
}
public LoginCollectionChoice(DataTable dtPermissions)
{
InitializeComponent();
GrdCollection.DataSource = dtPermissions;
dtPermit = dtPermissions;
}
private void btnChoose_Click(object sender, EventArgs e)
{
//Code for the user to choose a collection
ExitEvent(this, new EventArgs());
}
}
I’ve snipped all non-relevent code, I hope you gentlemen and ladies can help this newbie get on the right path. Please, be gentle, you wouldn’t want to see me cry, would you? :) Oh! And if you know of any great tutorial sites, please email them to me. I'd prefer to spend a week on tutorials than a week on stumbling and asking here. Thank you all very much.
Are you calling logonForm.Show()?
It seems like you'd need to show it that way.
You use BringToFront(), but I think it needs to be shown first.
The first thing that jumps out to me is that you are calling
LoginCollectionChoice LoginChoice = new LoginCollectionChoice(dtPermissions);
which is creating a local variable called LoginChoice, which is not the same as your class variable even though they share the same name.
What you want to do is to not declare a local variable in that method. Change that line to
LoginChoice = new LoginCollectionChoice(dtPermissions);
Having said that, I believe tylerjgarland in that you need to call .Show() first. And the way you are closing the form is certainly odd. I would create a form, showDialog, get the result and then close the form that way.

Refactoring big ball of mud; not sure static is being used properly here. Advice?

I'll admit sometimes the deeper nuances of the keyword static escape me.
Here's what I'm seeing:
public partial class Default : CSSDEIStatusBase
{
private static Default _csWitWeb;
protected void Page_Load(object sender, EventArgs e)
{
//DoStuff
_csWitWeb = this;
//OtherStuff
}
public static void ForceLoadSyncOperation(int? index)
{
Default._csWitWeb.LoadSelectedSyncOperation(index);
}
}
The only references to ForceLoadSyncOperation are:
Default.ForceLoadSyncOperation(index);
or
Default.ForceLoadSyncOperation(null);
Both of these calls originate from:
public partial class DataOriginUserControl : System.Web.UI.UserControl
and are not located inside of static methods.
E.G:
protected void btnCancelSyncOperation_Click(object sender, EventArgs e)
{
this.lblErrorMessage.Text = string.Empty;
this.lblErrorMessage.Visible = false;
int index = _syncOperation.Sequence - 1;
Default.ForceLoadSyncOperation(index);
}
This all seems really quirky to me. Does this smell to anyone else? Not really sure how to untangle it, though, as I can't exactly create an instance of the Default page inside of a user control.
Thoughts? Thanks for reading.
protected void LoadSelectedSyncOperation(int? index)
{
SyncOperationConfiguration[] syncOperations = CSServiceClient.GetInterfaceConfiguration().SyncOperationConfigurations.ToArray();
PopulateSyncOperationsListView(syncOperations);
SyncOperationConfiguration syncOperation = null;
try
{
syncOperation = syncOperations[index.HasValue ? index.Value : 0];
}
catch
{
syncOperation = syncOperations[0];
}
ucDataOrigin.LoadSyncOperationData(syncOperation);
Session["ConfigMenuActiveIndex"] = 1;
menuConfiguration.Items[(int)Session["ConfigMenuActiveIndex"]].Selected = true;
mvwConfiguration.ActiveViewIndex = (int)Session["ConfigMenuActiveIndex"];
}
Presumably, the user control is contained within the Default page and the static member is being used as a shortcut to get the current instance of Default. I would've done it this way:
Default defaultPage = this.Page as Default;
if (defaultPage != null)
{
defaultPage.LoadSelectedSyncOperation(index);
}
Using a static member in this way is not safe. It opens up the door for race conditions. There is the potential risk that the user control is loaded in another page and calls LoadSelectedSyncOperation() on a separate request's instance of Default, thus wreaking all kinds of potential havoc.
I don't know what LoadSelectedSyncOperation does but this code looks weird. Whenever you click btnCancelSyncOperation you end up calling this method on some page, but you never know on which of them. It doesn't make much sense to me.
I would definitely say your concerns are valid. I can't think of any reason that this design would make sense, ever. This would throw a flag for me, too.
Based on your reply to my comment, if the Default.LoadSelectedSyncOperation is not dependent upon the Default page somehow, then I suggest it be refactored into a separate class (not an ASP.NET Page).
Whether it makes sense for the method or new class to be static or not is a separate concern and would be based on the logic contained within the method.

Categories