Reputation: 337
private void frmExecute_Load(object sender, EventArgs e)
{
string[] data = File.ReadAllLines("c:\\toyotoconsole\\tssetup.txt");
// Loop through each line, split, add if server
for (int i = 0; i < data.Length; i++)
{
var serverValues = data[i].Split('|');
}
}
Okay first C# windows project, which is cool since I have never really touched this beyond the odd debugging foray.
My problem is the array serverValues
is built in a function, how do I make this array available for all functions (not sure if using the right term here) in the same form script (probably the wrong word there as well). Is there a public
declaration?
Upvotes: 0
Views: 654
Reputation: 186668
Technically, you should turn local variable serverValues
into a field (or property):
private string[] serverValues = new string[0];
private void frmExecute_Load(object sender, EventArgs e) {
...
serverValues = data[i].Split('|');
...
}
However, as one can see, you rewrite serverValues
within the loop; that's why serverValues
will contain the last line splitted only. Another issue is mixing Business logic (ServerValues
) and UI (form loading).
It seems you want something like this:
using System.Linq;
...
private string[] m_ServerValues = null;
// Pure buiness logic: ServerValues without any UI (form)
public string[] ServerValues {
get {
// If we have the array we return it
if (m_ServerValues != null)
return m_ServerValues;
// otherwise we compute it
m_ServerValues = File
.ReadLines("c:\\toyotoconsole\\tssetup.txt")
.SelectMany(line => line.Split('|'))
.ToArray();
// And return it
return m_ServerValues;
}
}
// UI: form loading
private void frmExecute_Load(object sender, EventArgs e) {
// If you want to prefetch (it's not necessary)
var values = ServerValues;
}
Upvotes: 3
Reputation: 1335
// Declare a private property in you class
private serverValues = Array.Empty<string>();
And then use within any event
private void frmExecute_Load(object sender, EventArgs e)
{
string[] data = File.ReadAllLines("c:\\toyotoconsole\\tssetup.txt");
// Loop through each line, split, add if server
for (int i = 0; i < data.Length; i++)
{
serverValues = data[i].Split('|');
}
}
Upvotes: 0