I am using LINQ to create tables in a WPF application, but when I try to access one of those tables using an event method, my compiler tells me "The name 'parts' does not exist in the current context". Is there something I should do to adjust the scope so that I can access a var from a separate method?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace FinalExam_SupplierPartsWPF
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
var suppliers = new[] {
new{SN = 1, SName = "Smith", Status = 20, City="London"},
new{SN = 2, SName = "Jones", Status = 10, City="Paris"},
new{SN = 3, SName = "Blake", Status = 30, City="Paris"},
new{SN = 4, SName = "Clark", Status = 20, City="London"},
new{SN = 5, SName = "Adams", Status = 30, City="Athens"}
};
var parts = new[] {
new{PN = 1, PName="Nut", Color = "Red", Weight = 12, City="London"},
new{PN = 2, PName="Bolt", Color = "Green", Weight = 17, City="Paris"},
new{PN = 3, PName="Screw", Color = "Blue", Weight = 17, City="Rome"},
new{PN = 4, PName="Screw", Color = "Red", Weight = 14, City="London"},
new{PN = 5, PName="Cam", Color = "Blue", Weight = 12, City="Paris"},
new{PN = 6, PName="Cog", Color = "Red", Weight = 19, City="London"}
};
var shipment = new[] {
new{SN = 1, PN = 1, Qty=300},
new{SN = 1, PN = 2, Qty=200},
new{SN = 1, PN = 3, Qty=400},
new{SN = 1, PN = 4, Qty=200},
new{SN = 1, PN = 5, Qty=100},
new{SN = 1, PN = 6, Qty=100},
new{SN = 2, PN = 1, Qty=300},
new{SN = 2, PN = 2, Qty=400},
new{SN = 3, PN = 2, Qty=200},
new{SN = 4, PN = 2, Qty=200},
new{SN = 4, PN = 4, Qty=300},
new{SN = 4, PN = 5, Qty=400}
};
IEnumerable<string> colorList = parts
.OrderBy(part => part.Color)
.Select(part => part.Color)
.Distinct();
foreach (string x in colorList)
cbxColorSelect.Items.Add(x);
}
private void ColorSelectedEvent(object sender, SelectionChangedEventArgs e)
{
lbxPartDisplay.Items.Add("test");
string colorChoice = cbxColorSelect.Text;
IEnumerable<string> partResults = parts
.Where(clr => String.Equals(clr.Color, colorChoice))
.Select(part => String.Format("{0}", part.PName));
foreach (string y in partResults)
lbxPartDisplay.Items.Add(y);
}
}
}
MainWindowconstructor has completed by the timeColorSelectedEventruns... the variable is long gone. If you need to keep it, you'll need it to be a field rather than a local variable. I would strongly recommend that you learn the basics of C# with console apps before moving onto GUIs - there are a lot fewer moving parts to worrying about that way.