Can't figure out why Object reference is null - c#

Working on a program for class, and am about 95% complete, but have run into a roadblock. I've got a Flight class that holds information about the flight, as well as a seating chart. Using a windows form listbox to select from the flight objects I created by reading from a text file. I can get values for every property from the class object, except for one, SeatChart.
Here's the pertinent code in the main program:
private void lstFlights_SelectedIndexChanged(object sender, EventArgs e)
{
curFlight = (Flight)lstFlights.SelectedItem;
DisplayNewFlightChart();
}
private void DisplayNewFlightChart()
{
int seats = curFlight.Rows * curFlight.Seats;
lstSeatingChart.Items.Clear();
string[] seatChart = curFlight.SeatChart;
for (int x = 0; x <= seats; x++)
{
lstSeatingChart.Items.Add("Seat " + (x + 1) + " " + seatChart[x]);
}
}
And here is the code from the class:
class Flight
{
private string mPlane;
private string mDepartureTime;
private string mDestination;
private int mRows;
private int mSeats;
private string[] mSeatChart;
public Flight()
{
}
// Create the overloaded Constructor
public Flight(string planeType, string departureTime,
string destination, int numRows,
int numSeatsPerRow)
{
this.Plane = planeType;
this.DepartureTime = departureTime;
this.Destination = destination;
this.Rows = numRows;
this.Seats = numSeatsPerRow;
this.SeatChart = mSeatChart;
mSeatChart = new string[Rows * Seats];
for (int seat = 0; seat <= mSeatChart.GetUpperBound(0); seat++)
{
mSeatChart[seat] = "Open";
}
}
public string Plane
{
get { return mPlane; }
set { mPlane = value; }
}
public string DepartureTime
{
get { return mDepartureTime; }
set { mDepartureTime = value; }
}
public string Destination
{
get { return mDestination; }
set { mDestination = value; }
}
public int Rows
{
get { return mRows; }
set { mRows = value; }
}
public int Seats
{
get { return mSeats; }
set { mSeats = value; }
}
public string[] SeatChart
{
get { return mSeatChart; }
set { mSeatChart = value; }
}
public void MakeReservation(string passName, int seat)
{
bool seatTaken = false;
if (mSeatChart[seat] != "Open") seatTaken = true;
if (passName != "" && seatTaken == false)
{
mSeatChart[seat] = passName;
}
else
{
MessageBox.Show("Please Enter a Passenger Name, in an unreserved seat");
}
}
It's telling me the curFlight.SeatChart is null, even though I can pull .Rows and .Seats from the curFlight just fine. I have no clue why .SeatChart is messing up. lstFlights is the list of flight objects pulled from the text file, and lstSeatingChart is where I want to display a list of seats.

You are setting SeatChart to mSeatChart, which is null at that time. So no reference to an object is made for this.SeatChart.
After that you initialize mSeatChart and fill it.
You should move setting this.SeatChart after initializing mSeatChart.
mSeatChart = new string[Rows * Seats];
this.SeatChart = mSeatChart;
Edit:
In addition, SeatChart is the property and mSeatChart is the member variable. SeatChart will be used to expose mSeatChart, so it's really weird to set SeatChart with mSeatChart. So weird that I didn't even think you were doing that.
So in your case leave the following out in the constructor:
this.SeatChart = mSeatChart;
I think the actual cause of your issue is somewhere else in the code, where you initiate Flight and fill the list. If I understand correctly you get a null reference error on the concatenation in the for loop?
string[] seatChart = curFlight.SeatChart;
for (int x = 0; x <= seats; x++)
{
lstSeatingChart.Items.Add("Seat " + (x + 1) + " " + seatChart[x]);
}
Check where you initate each Flight object. I bet you are using the empty constructor: new Flight()
Remove the empty constructor, because you don't expect empty values apparently. And if you really need the empty constructor then either initiate all member variables as expected or perform a null check wherever you want to use them.
And once you found the cause, make sure you change the for loop to
for (int x = 0; x < seats; x++)
since you are checking for the number of seats and do a zero-based loop. If x = seats you would have performed the loop seats + 1 times (rows*seats + 1).

If your code relies on a particular property never being null, you need to make sure it is initialized in all constructors.
Based on the logic of your class, I would suggest you shouldn't have a parameter less constructor. It doesn't make sense to have a flight that didn't have a known number of seats (in your implementation at least).
Also some style things.
You don't need to declare your private instance variables. Just use
public string destination {get; set;}
Declare "open" as a class constant and use that constant rather than the hard coded string value.

Related

C# - How to create a common method to update different properties in a object without creating multiple methods

This is my object
public class Totals {
public int Total1 { get; set; }
public int Total2 { get; set; }
public int Total3 { get; set; }
public int Total4 { get; set; }
}
Incrementing the values of Total1 and Total2 using calculateTotals method
private Totals calculateTotals(Totals t) {
if (//condition) {
t.Total1 += 1;
} else {
t.Total2 += 1;
}
return t;
}
**Incrementing value of Total3 and Total4 of the same object with same conditions at a different location using different method calculateOtherTotals, at this point I only need to update Total3 and Total4 **
private Totals calculateOtherTotals(Totals t) {
if (//condition) {
t.Total3 += 1;
} else {
t.Total4 += 1;
}
return t;
}
I am new to c# , I need to increment the values Total1,Total2 and Total3,Total4 separately and the code which I have is working fine
Is there a way to improve my code?, how can I avoid creating two different methods which pretty much does the same logic on different properties? is there a way to create only 1 method to achieve my functionality?
You could do it this way, but essentially the amount of code doesn't change.
This adds a judgment:
Totals calculateTotals(Totals t, bool Flag)
{
//function1:
if (Flag)
{
if (true)
{ //(condition) {
t.Total1++;
}
else
{
t.Total2++;
}
}
//function2:
else
{
if (true)
{ //(condition) {
t.Total3++;
}
else
{
t.Total4++;
}
}
return t;
}
Call it like this:
Totals totals = new Totals();
totals.Total1=0;
totals.Total2=0;
totals.Total3=0;
totals.Total4=0;
calculateTotals(totals,true);//function1:
calculateTotals(totals,false);//function2:
Reflection is one way, though its slow and not a Domain Specific Language:
Type totalsType = typeof(Totals);
var totalToIncrement = condition;
PropertyInfo prop = totalsType.GetProperty("Total" + totalToIncrement);
prop.SetValue(null, 76);
Or perhaps you want to abstract the properties you're incrementing:
private Totals calculateTotals(Totals t)
{
bool condition = true;
AbstractAdds(ref t.Total1, ref t.Total2, condition);
return t;
}
private void AbstractAdds(ref int a, ref int b, bool condition = false)
{
if (condition)
{
a++;
}
else
{
b++;
}
}
}
public class Totals
{
public int Total1;//{ get; set; }
public int Total2;//{ get; set; }
public int Total3;//{ get; set; }
public int Total4;//{ get; set; }
}
I'd personally have a List<int> or int[3] and make the condition calculate the index 0-3:
var index = calcCondition;
Totals[index]++;
This way its extensible for more totals and you get inbuilt functions like LINQ, eg Totals.Sum().
Is there a way to improve my code?, how can I avoid creating two different methods which pretty much does the same logic on different properties? is there a way to create only 1 method to achieve my functionality?
Then it depends on how you want your method (function) to be. (E.g., how you define what your function will do and how your class and properties are characteristic—which, currently, many who want to help you still wonder about.)
Let me give another clear example.
Assume that you answer your additional requirement are:
My object has only 4 properties of "Total"
I want these new function to increment value only 1 when call, no need to add more than 1
This function is called from another class to modify my object value
I want my cool function name calculateOtherTotals being private, because of some unexplained reason such as “I don't like others knowing it exists”.
Then
public OtherClass{
Public Totals ExposeThePrivateCalculateOtherTotals(Totals t, bool IncrementT1 , bool IncrementT2 , bool IncrementT3, bool IncrementT4)
{
calculateOtherTotals(t, IncrementT1 , IncrementT2 , IncrementT3, IncrementT4);
}
Private Totals calculateOtherTotals(Totals t, bool IncrementT1 , bool IncrementT2 , bool IncrementT3, bool IncrementT4) {
if( IncrementT1 ) t.Total1 += 1; //choose your style
if( IncrementT2==true ) ++t.Total2;//choose your style
if( IncrementT3!=false ) t.Total3++; //choose your style
t.Total4 += IncrementT4==true?1:0;//choose your style
return t;
}
}
//In main (how to use)
Totals t= new Totals();
OtherClass doMyFunc = new OtherClass();
t = doMyFunc.ExposeThePrivateCalculateOtherTotals(t, true, false,false,false); // result of operation => t.total1 += 1;
t = doMyFunc.ExposeThePrivateCalculateOtherTotals(t, false, true,false,false); // result of operation => t.total2 += 1;

run a FOR loop to create 4 plumbers from the default constructor c#

As you see in the title above, i need to run a FOR loop to create 4 plumbers from the default constructor. After they are created (within the FOR loop), change their names, add them to the employee list and display in listbox. So basically, plumbers is actually a list declared in another class called EmployeeList. Wehn i tried changing their names to random ones, i get like an error msg saying 'Index is out of range'. Can someone help me with this?
Form Code
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//create class-level employee list
EmployeeList plumbers = new EmployeeList();
private void Form1_Load(object sender, EventArgs e)
{
//run a for loop to create 4 plumbers from the default constructor.
for (int i = 0; i < plumbers.Count; i++)
plumbers[i] = new Employee();
//After they are created (within the FOR loop), change their names,
//plumbers[0].Name = "Nicole Fernandez";
//add them to the employee list
//display in listbox
foreach (Employee item in plumbers.Employees)
{
lstDisplay.Items.Add(item.DisplayData());
}
}
Employee List Class Code
class EmployeeList
{
//use private access modifier to create a list of employee
private List<Employee> employees = new List<Employee>();
public List<Employee> Employees
{
get { return employees; }
set { employees = value; }
}
//return the count of the employee list, use lambda operator
public int Count => employees.Count();
//create default constructor
public EmployeeList() { }
//create a method that adds employee sent to the list. No return value
public void AddEmp(Employee emp)
{
employees.Add(emp);//add employee to the list
}
//create employee from data sent. No return value
public void AddEmp(string inName, int inID, decimal inHourlyWage)
{
//declare a variable
Employee emp = new Employee(inName, inID, inHourlyWage);
//call the other AddEmp
AddEmp(emp);
}
//create a method that deletes employee from the list. No return value
public void DeleteEmp(Employee emp) => employees.Remove(emp);
//insert employee at the index
public void InsertEmp(Employee emp, int index) => employees.Insert(index, emp);
//create an indexer
public Employee this[int i]
{ //q12 - indexer property with exception
get
{
if (i < 0 || i >= Count)
throw new ArgumentOutOfRangeException(i.ToString());
return employees[i];
}
set { employees[i] = value; }
}
}
Employee Class Code
class Employee
{
//use auto-implemented property
public int ID { get; set; }
public string Name { get; set; }
public decimal HourlyWage { get; set; }
public decimal TotalPay { get; set; }
//create static integer that starts at 1
private static int NextID = 1;
//create a default constructor with default values
public Employee()
{
ID = NextID++;
Name = "John Doe";
HourlyWage = 15.25m;
TotalPay = 0.0m;
}
//create the custom constructor sending in 3 parameters
public Employee(string inName, int inID, decimal inHourlyWage)
{
Name = inName;//set name, no validation is required
//validate ID is between 1 and 250. if not, set to nextID available
if (inID <= 1 && inID >= 250)
NextID = inID;
//validate hourly wage is between 12.50 and 20. If not, set to 15.25
if (inHourlyWage <= 12.50m && inHourlyWage >= 20.0m)
inHourlyWage = 15.25m;
TotalPay = 0;//set total pay to 0
}
public string DisplayData() => ID + "\t" + Name + "\t" + HourlyWage.ToString("c") + "\t" + TotalPay.ToString("c");
}
First, if you want to create a list of 4 plumbers using a loop, then you need the loop to iterate 4 times. This is normally done by setting the initial counter value to 0, then looping while it is less than the number you want:
for (int i = 0; i < 4; i++)
Also, your plumbers object is of type EmployeeList, but you're trying to access it with an indexer as if it's a List or an Array. Instead, you should use the method you created to add new employees:
// Run a for loop to create 4 plumbers from the default constructor.
for (int i = 0; i < 4; i++)
{
plumbers.AddEmp(new Employee());
}
Since there doesn't appear to be any public method to update an existing plumber, we can just access the Employees list directly to rename the plumbers. There are a couple of ways to do it. One would be to use a loop and use part of the loop counter in the name:
// After they are created (within the FOR loop), change their names
for(int i = 0; i < plumbers.Employees.Count; i++)
{
plumbers.Employees[i].Name = string.Format("Plumber #{0}", i);
}
Another way is to do it by hand, giving each plumber a normal name:
plumbers.Employees[0].Name = "Nicole";
plumbers.Employees[1].Name = "Rufus";
plumbers.Employees[2].Name = "Mark";
plumbers.Employees[3].Name = "John";
Or, if you want to be really fancy, you can generate a list of names (I pulled these from the top baby names of 2016), then for each plumber grab a random name from the list and assign it (and remove it from the list so the plumbers all have unique names):
//After they are created (within the FOR loop), change their names
// Generate a list names
var nameCandidates = new List<string>
{
"Olivia", "Amelia", "Charlotte", "Ava", "Isla", "Arabella", "Aurora",
"Adeline", "Penelope", "Eleanor", "Ezra", "Asher", "Atticus",
"Declan", "Oliver", "Silas", "Milo", "Levi", "Henry", "Wyatt"
};
// Loop through each plumber and choose a random name
var rnd = new Random();
foreach(var plumber in plumbers.Employees)
{
// Choose a random name, assign it, and remove it from candidates
var nameIndex = rnd.Next(nameCandidates.Count);
plumber.Name = nameCandidates[nameIndex];
nameCandidates.RemoveAt(nameIndex);
}

The get and set property appears to be ignored (C#)

I'm trying to modify the "set" portion, but these changes don't seem to take place at all. Here is the basic code that shows the same results:
class Class1
{
private int num;
public Class1(int number)
{
num = number;
}
public int getNumber
{
get
{
return num;
}
set
{
if (value > 0)
num = value;
else
num = 0;
}
}
}
In here, I want to make any negative value a 0.
class Program
{
static void Main(string[] args)
{
Class1 c1 = new Class1(10);
Class1 c2 = new Class1(-10);
Console.WriteLine(c1.getNumber);
Console.WriteLine(c2.getNumber);
Console.ReadLine();
}
}
The result gives me
10
-10
I've tried using
set
{
num = 100;
}
yet there's still no change in the results. I've tried double checking with the book I'm using, and there's no difference that I can see. I'm using Visual Studio 2012 if it means anything.
Your code is not calling set portion of your property. Because, you are only calling constructor. And in your constructor you are only setting tha value for the backing field variable(num).
Also, by convention, your class members names are not appropriate.
Change it as:
num -> number getNumber -> Number
Try this:
Class1 c1 = new Class1();
c1.Number = -10; // The set accessor is invoked here
int myNumber = c1.Number; // The get accessor is invoked here
If you want to invoke set accessor through your constructor, then change your constructor as:
public Class1(int number)
{
Number = number;
}
Then it will invoke set accessor properly:
Class1 c1 = new Class1(10); // The set accessor will be invoked
And don't forget to change your class implementation as:
class Class1
{
private int number;
public int Number
{
get { return number; }
set
{
if (value > 0)
number = value;
else
number = 0;
}
}
// If you do provide a constructor (any constructor with any signature),
// the parametrless constructor will not be generated
public Class1()
{
}
public Class1(int number)
{
Number = number;
}
}
Read this from msdn for additional information.
Try this:
class Class1
{
private int num;
public Class1(int number)
{
Number = number;
}
public int Number
{
get
{
return num;
}
set
{
if (value > 0)
num = value;
else
num = 0;
}
}
}
You hadn't implented it correctly. Actually a better implmentation would be the following:
class Class1
{
// The backing field has the same name as the Property
// but all letters must be lowercase.
private int number;
public int Number
{
get { return number; }
set
{
if (value > 0)
number = value;
else
number = 0;
}
}
// In the constructor we set the value of the backing fields
// using the corresponding properties.
public Class1(int number)
{
Number = number;
}
}
The each time you want to set the value of number or get it's value you use the corresponding property:
// Set the value 2 to the number
Number = 2;
// Read the value stored in number and assigned to value.
var value = Number;

Variable not returning actual values

I want correctly return some variables (arrays)
kazkas.Ads[n]; (n = how many ads are)
kazkas.Ads[n].id;
kazkas.Ads[n].Days[m].Stats.Clicks; // every day have his own clicks
kazkas.Ads[n].Days[m].Stats.Impresons; // every day have his own impresions
from this method and use these variables in other class.
public static void GetAdsStats(string Ticket, DateTime start, DateTime end, int CamId)
{
var client = new CampaignStatsServiceClient();
var id = new CampaignIdFilter();
id.CampaignId = CamId;
var statsdata = new GetAdStatsData();
var kazkas = new Campaign();
kazkas = client.GetAdStats(Ticket, new GetAdStatsData
{
IdFilter = id,
StartDate = start,
EndDate = end
});
long AllClicks = 0;
long AllImpresions = 0;
int reklamos = kazkas.Ads.Length;
long[] statistikaClikai = new long[reklamos];
long[] statistikaImpresions = new long[reklamos];
for (int i = 0; i < reklamos; i++)
{
int dienos = kazkas.Ads[i].Days.Length;
for (int lop = 0; lop < dienos; lop++)
{
AllClicks = AllClicks + kazkas.Ads[i].Days[lop].Stats.Clicks;
AllImpresions = AllImpresions + kazkas.Ads[i].Days[lop].Stats.Impressions;
}
statistikaClikai[i] = AllClicks;
statistikaImpresions[i] = AllImpresions;
}
}
I know that void type can't return anything, but this how I know that my method works ( from debugging). Like you see I was trying do that with for loop. Here i have 9 Ads and every ad have one day.
Like I says I want return every Ads id[in array], and every days.stats.impresions and days.stats.click
how can I do that ? Ore how return more variables/arrays from method to other class, I am using webservises, so i cant use database ore something like that.
As can be seen by the downvotes of the question, you need to design the return value and then code against it.
Your query almost does it (now):
kazkas.Ads[n]; (n = how many ads are)
kazkas.Ads[n].id;
kazkas.Ads[n].Days[m].Stats.Clicks; // every day have his own clicks
kazkas.Ads[n].Days[m].Stats.Impressions; // every day have his own impressions
Your existing code show this should be expanded to include:
kazkas.Ads[n].Total.Clicks;
kazkas.Ads[n].Total.Impressions;
So now you're ready to design. First you want a Stat Class that just contains CLicks and Impressions:
public class Stat
{
public long Impressions { get; set; }
public long Clicks { get; set; }
}
An optimisation here may be to use a struct, but I won't go into that.
As you currently have defined it each Day has just a Stats property:
public class DayStat
{
public Stat Stats { get; set; }
}
Now finally we can define the top level AdStat:
public class AdStat
{
public int id { get; set; }
public DayStat Day[];
public Stat Total { get; set; }
}
Etc... There's further issues here, such as ensuring arrays are created and Stat instances are never null (which is why making some of these classes structs is an option). But I'm really a VB programmer so I'll stop here before I get caught typing crap into the SO IDE :-)
Create a class or struct with members you need
public class Stat
{
public int Id { get; set; }
public long Clicks { get; set; }
...
}
Change the signature of your method from void GetAdsStats to IEnumberable<Stat> GetAdsStats and either return a collection of stats or use yield keyword to return the stat object.
Also if you do not want your method to return anything (return type void) do not use a name starting with Get.
Example:
public static IEnumerable<Stat> GetAdsStats(...)
{
...
var statList = new List<Stat>();
for (int i = 0; i < reklamos; i++)
{
var stat = new Stat();
statList.Add(stat);
int dienos = kazkas.Ads[i].Days.Length;
for (int lop = 0; lop < dienos; lop++)
{
AllClicks = AllClicks + kazkas.Ads[i].Days[lop].Stats.Clicks;
AllImpresions = AllImpresions + kazkas.Ads[i].Days[lop].Stats.Impressions;
}
stat.Clicks = AllClicks;
stat.Impression = AllImpresions;
}
return statList;
}
Change your void to the type you want to return, say Campaign, and return the appropriate variable. The variables you define in your method, only live in your method and are not accessible from another method or class.

Trying to make it so when i click on my windows forms button, the next 3 numbers from my textfile are shown

Here is the code below.
I am trying to make it so that when I click on the nextButton button it cycles to the next 3 numbers in my textfile. I cant figure out ow, what i have here should work :[
namespace GPSProject
{
class dataPoints
{
public int Count { get { return Points.Count; } }
List<dataPoint> Points;
//string p;
public dataPoints(/*string path*/)
{
Points = new List<dataPoint>();
// p = path;
TextReader tr = new StreamReader(/*p*/"C:/Test.txt");
string input;
while ((input = tr.ReadLine()) != null)
{
string[] bits = input.Split(',');
dataPoint a = new dataPoint(bits[0], bits[1], bits[2]);
Points.Add(a);
}
tr.Close();
}
internal dataPoint getItem(int p)
{
if (p < Points.Count)
{
return Points[p];
}
else
return null;
}
}
}
Above is the class that breaks down the textfile into inidividual numbers.
namespace GPSProject
{
public partial class Form1 : Form
{
private int count;
internal dataPoints myDataPoints;
public Form1()
{
myDataPoints = new dataPoints();
InitializeComponent();
}
private void buttonNext_Click(object sender, EventArgs e)
{
{
count++;
if (count == (myDataPoints.Count))
{
count = 0;
}
dataPoint a = myDataPoints.getItem(count);
textBoxLatitude.Text = a.CurLatitude;
textBoxLongtitude.Text = a.CurLongtitude;
textBoxElevation.Text = a.CurElevation;
}
}
}
}
Above is the Windows form
namespace GPSProject
{
class dataPoint
{
private string latitude;
private string longtitude;
private string elevation;
public dataPoint() //Overloaded incase no value available
{
latitude = "No Latitude Specified";
longtitude = "No Longtitude Specified";
elevation = "No Elevation Specified";
}
public dataPoint(string Latitude, string Longtitude, string Elevation)
{
// TODO: Complete member initialization
this.latitude = Latitude;
this.longtitude = Longtitude;
this.elevation = Elevation;
}
public string CurLongtitude { get { return this.longtitude; } }
public string CurLatitude { get { return this.latitude; } }
public string CurElevation { get { return this.elevation; } }
}
}
And finally this is the class the holds the numbers. The numbers i am trying to get the textboxes to show are cycles of CurLongtitude/Latitue/Elevation
First thing to do would be to create a proper vessle for your data: the DataPoint Entity:
class DataPoint
{
// Option 1: Field + read only property
private string _latitude;
public string Latitude { get { return _latitude; } }
// Option 2: Property + compiler generated field
public string Longitude { get; private set; }
public string Elevation { get; private set; }
// Constructor
public DataPoint(string latitude, string longtitude, string elevation)
{
// Internally in this class we use fields
_latitude = latitude;
// Unless we use property option 2
this.Longitude = longitude;
this.Elevation = elevation;
}
}
Next we could add a static method to the DataPoint class to load the data points from disk:
public static List<DataPoint> LoadFromFile (string filename)
{
// The .NET framework has a lot of helper methods
// be sure to check them out at MSDN
// Read the contents of the file into a string array
string[] lines = File.ReadAllLines(filename);
// Create the result List
List<DataPoint> result = new List<DataPoint>();
// Parse the lines
for (string line in lines)
{
string[] bits = line.Split(',');
// We're using our own constructor here
// Do watch out for invalid files, resulting in out-of-index Exceptions
DataPoint dataPoint = new DataPoint(bits[0], bits[1], bits[2]);
result.Add(dataPoint);
}
return result;
}
Now that we have all the building blocks. Let's make the application:
public partial class Form1 : Form
{
private int _index;
private List<DataPoint> _dataPoints;
public Form1()
{
// Since this is a simple test application we'll do the call here
_dataPoints = DataPoint.LoadFromFile(#"C:\Test.txt");
InitializeComponent();
}
private void buttonNext_Click(object sender, EventArgs e)
{
// Cycle the data points
_index++;
if (_index == _dataPoints.Count)
{
_index = 0;
}
// Get the specific data point
DataPoint dataPoint = _dataPoints[_index];
// The empty texts are UI only, so we could check them here
if (dataPoint.Latitude == null || dataPoint.Latitude == "")
{
textBoxLatitude.Text = "No Latitude Specified";
}
else
{
textBoxLatitude.Text = dataPoint.Latitude;
}
// A shorter, inline version
textBoxLongtitude.Text = String.IsNullOrEmpty(dataPoint.Longitude) ? "No Longitude Specified" : dataPoint.Longitude;
// Or if we don't care about empty texts
textBoxElevation.Text = dataPoint.Elevation;
}
}
Of course there are lots of ways to make the code even shorter, or to use modern techniques like LINQ, but I've tried not to go too far from your existing code. I haven't tried the code, I typed it here on SO :)
Also please be careful in how you format your code. Proper casing and following standards makes your code a lot easier to read by others.
MSDN has a lot of good examples and extensive documentation on the .NET Framework classes.

Categories