C
C#5mo ago
ILikeCats!

2 error abt variables

details: VS 2022, FILE: form1.cs errors: ```Severity Code Description Project File Line Suppression State Error (active) CS0236 A field initializer cannot reference the non-static field, method, or property 'Form1.savepath2' excelbetter C:\Users(user hidden for pivacy)\source\repos\excelbetter\excelbetter\Form1.cs 8

### error 2:

### error 2:
Severity Code Description Project File Line Suppression State Error (active) CS0236 A field initializer cannot reference the non-static field, method, or property 'Form1.workingFile' excelbetter C:\Users\nuh uh\source\repos\excelbetter\excelbetter\Form1.cs 9
var names for errors `workingFile`, `savepath2`
### code \\/
var names for errors `workingFile`, `savepath2`
### code \\/
using ClosedXML.Excel; namespace excelbetter { public partial class Form1 : Form { public string savepath2 = @"C:\Users\nuh uh\excel" + "YIPPE.xlsx"; public XLWorkbook workingFile = new XLWorkbook(savepath2); public IXLWorksheet spreadsheet1 = workingFile.AddWorksheet("s"); public Form1() { InitializeComponent(); } public void process_Data_Click(object sender, EventArgs e) { Close(); } } } ```
7 Replies
Pobiega
Pobiega5mo ago
well, as said - your field initializers cant access the members they are trying to you need to move that code to the constructor
ILikeCats!
ILikeCats!OP5mo ago
huh
Pobiega
Pobiega5mo ago
initializers are limited in what they can do. they cant access other non-static members, since those might not have been initialized yet its a chicken and egg type thing so you need to initialize them inside your constructor instead
ILikeCats!
ILikeCats!OP5mo ago
so define them as what they are?
Pobiega
Pobiega5mo ago
yes, feel free to define them there but give them their value in the ctor
ILikeCats!
ILikeCats!OP5mo ago
so first define like XLWorkbook (varname); then XLWorkbook (varname) = ("BLEH")
Pobiega
Pobiega5mo ago
something like that, yeah
using ClosedXML.Excel;

namespace excelbetter;

public partial class Form1 : Form
{
private const string savepath2 = @"C:\Users\nuh uh\excel\YIPPE.xlsx";
private XLWorkbook _workingFile;
private IXLWorksheet _spreadsheet1;

public Form1()
{
_workingFile = new XLWorkbook(savepath2);
_spreadsheet1 = _workingFile.AddWorksheet("s");

InitializeComponent();
}

public void process_Data_Click(object sender, EventArgs e)
{
Close();
}
}
using ClosedXML.Excel;

namespace excelbetter;

public partial class Form1 : Form
{
private const string savepath2 = @"C:\Users\nuh uh\excel\YIPPE.xlsx";
private XLWorkbook _workingFile;
private IXLWorksheet _spreadsheet1;

public Form1()
{
_workingFile = new XLWorkbook(savepath2);
_spreadsheet1 = _workingFile.AddWorksheet("s");

InitializeComponent();
}

public void process_Data_Click(object sender, EventArgs e)
{
Close();
}
}
Want results from more Discord servers?
Add your server