I have assigned two string array:
string[] SelectColumns = {},WhereColumns={};
Both of them are full of data items. For example SelectColumns.length = 7,WhereColumns.Length=3;
When i went to implement them i got an exception: object reference not set to an instance of an object.
I am using them in below:
for (int i = 0; i < SelectColumns.Length; i++)
{
DPS._SelectCol[i] = SelectColumns[i];
}
for (int i = 0; i < WhereColumns.Length; i++)
{
DPS._WhereCol[i] = WhereColumns[i];
}
Here DPS is the object of a class, which is given below:
public class DefaultProfileSetting
{
private string Server;
public string _Server
{
get { return Server; }
set { Server = value; }
}
private string Authentication;
public string _Authentication
{
get { return Authentication; }
set { Authentication = value; }
}
private string Login;
public string _Login
{
get { return Login; }
set { Login = value; }
}
private string Pass;
public string _Pass
{
get { return Pass; }
set { Pass = value; }
}
private string DB;
public string _DB
{
get { return DB; }
set { DB = value; }
}
private string Table;
public string _Table
{
get { return Table; }
set { Table = value; }
}
private string[] SelectCol;
public string[] _SelectCol
{
get { return SelectCol; }
set { SelectCol = value; }
}
private string[] WhereCol;
public string[] _WhereCol
{
get { return WhereCol; }
set { WhereCol = value; }
}
}
You probably have just string array reference _SelectCol but not actual array and need to instantiate the _SelectCol string array to allocate memory to its elements.
DPS._SelectCol = new string [SelectColumns.Length];
for (int i = 0; i < SelectColumns.Length; i++)
{
DPS._SelectCol[i] = SelectColumns[i];
}
I don't see anywhere in DefaultProfileSetting where you initialize the fields behind _WhereCol and _SelectCol, so these are null.
At the least you should have:
private string[] SelectCol = new string[size];
Though these should have some sort of initial population or you will get IndexOutOfBoundsException as well.
Most probably your DPS array properties are not initialized with the correct length.
You'd best place a break point and debug your solution, so that you can see for you self where exactly it goes wrong.
If you say that SelectColumns and WhereColumns are already filled with values, then i bet that DPS._SelectCol is causing problems.
You have to initialize that array at the right size. Something like :
DPS._SelectCol = new string[SelectColumns.Length];
If you leave your arrays behind and start using List then you don't have these problems anymore.
Related
I just want my ComboBox to show me the
FullName of objects in List(Curator),
but it show me the same "object.FullName" multiple times :-(
-
Basically, it work cause it show me the FullName of ONE of the Curator,
and the good amount of times,
but it show me the same ONE !
public partial class SGIArt : Form
{
public static Gallery gal = new Gallery(); // from a dll i made
List<Curator> curList = new List<Curator>();
public SGIArt()
{
InitializeComponent();
comboCur.DataSource = curList;
comboCur.ValueMember = null;
comboCur.DisplayMember = "FullName";
UpdateCurList();
}
public void UpdateCurList()
{
curList.Clear();
foreach (Curator cur in gal.GetCurList())
// from the same dll : Curators curatorsList = new Curators();
{
curList.Add(cur);
}
}
private void comboCur_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboCur.SelectedValue != null)
{
//show info in textBox (that work fine)
}
}
}
Curator class :
public class Curator : Person
{
private int id;
private double commission;
const double commRate = 0.25;
private int assignedArtists = 0;
public int CuratorID
{
get
{
return id;
}
set
{
id = value;
}
}
...
public Curator()
{
}
public Curator(string First, string Last, int curID)
: base(First, Last) // from : public abstract class Person
{
id = curID;
commission = 0;
assignedArtists = 0;
}
Edit: You might be looking for this answer.
I do not see the FullName member in your code snippet. I think you are looking for something like this:
List<Curator> curList = new List<Curator>();
public SGIArt()
{
InitializeComponent();
comboCur.DataSource = datasource;
comboCur.ValueMember = null;
comboCur.DisplayMember = "FullName";
UpdateCurList();
}
List<string> datasource()
{
List<string> datasource = new List<string>();
foreach(Curator curator in curList)
{
datasource.Add(curator.FullName)//this assume FullName is an accesible member of the Curator class and is a string.
}
return datasource;
}
The comboBox shows you object.FullName, because this is what you are telling it. The curList is empty at the time when you bind it.
You can update your list before using it:
public SGIArt()
{
InitializeComponent();
UpdateCurList();
comboCur.DataSource = curList;
comboCur.ValueMember = null;
comboCur.DisplayMember = "FullName";
}
I was looking for a similar way to create an alias for something else like its possible in C using preprocessor (this question is a bit similar, couldn't find anything useful there).
This is the problem: I've got a method that receives an array, but each position of the array has a specific meaning, like they where different parameters with specific names. What I want to do is to make my code easier to read (and write) by using those specific names, but, on the other hand, I don't want to create another method call (like in example 1) nor assign the array positions to new variables (example 2), because the performance is critical.
Example 1:
void OriginalMethodSignature(Type[] values)
{
SimplifiedMethod(values[0], values[1], ... values[n]);
}
void SimplifiedMethod(Type specificName1, Type specificName2, ... Type specificNameN)
{
// simple implementation using specific names instead of values[n]
}
Example 2:
void OriginalMethodSignature(Type[] values)
{
Type specificName1 = values[0];
Type specificName2 = values[1];
...
Type specificNameN = values[n];
// simple implementation using specific names instead of values[n]
}
I cannot change the method signature because its used in a dellegate, the Type is fixed.
The next example is a bit better, but still not optimum:
void OriginalMethodSignature(Type[] values)
{
// implementation using values[specificName1] ... values [specificNameN]
}
const int specificName1 = 0;
const int specificName2 = 1;
...
const int specificNameN = n-1;
Is there any way to create an snippet for this purpose? If yes, how would it be?
There isn't any built in way to do what you wan't, because you shouldn't really be doing it at all. You should be using an object with properties instead of an array.
Anyway, you can make an object that encapsulates the array, so that the properties use the array as storage:
public class NamedObject {
private Type[] _values;
public NamedObject(Type[] values) {
_values = values;
}
public SpecificName1 { get { return _values[0]; } set { _values[0] = value; } }
public SpecificName2 { get { return _values[1]; } set { _values[1] = value; } }
public SpecificName3 { get { return _values[2]; } set { _values[2] = value; } }
public SpecificName4 { get { return _values[3]; } set { _values[3] = value; } }
public SpecificName5 { get { return _values[4]; } set { _values[4] = value; } }
public SpecificName6 { get { return _values[5]; } set { _values[5] = value; } }
}
Now you can use the object to access the array:
void OriginalMethodSignature(Type[] values) {
NamedObject obj = new NamedObject(values);
// get a value
Type x = obj.SpecificName4;
// set a value
obj.SpecificName2 = x;
}
Create a dedicated class or struct, and parse the array into it.
public class MyClassOfStuff
{
Type SpecificName1 {get;set;}
Type SpecificName2 {get;set;}
public static MyClassOfStuff Parse(Type[] value)
{
Type specificName1 = values[0];
Type specificName2 = values[1];
...
Type specificNameN = values[n];
}
}
void OriginalMethodSignature(Type[] values)
{
var mystuff = MyClassOfStuff.Parse(values);
}
I have a problem which I don't know how to solve. I have a class. This class has two arrays. I would like to get access via properties. How can I do it? I tried to use indexers, but it is possible if I have only one array. Here what I want to do:
public class pointCollection
{
string[] myX;
double[] myY;
int maxArray;
int i;
public pointCollection(int maxArray)
{
this.maxArray = maxArray;
this.myX = new string[maxArray];
this.myY = new double[maxArray];
}
public string X //It is just simple variable
{
set { this.myX[i] = value; }
get { return this.myX[i]; }
}
public double Y //it's too
{
set { this.myY[i] = value; }
get { return this.myY[i]; }
}
}
With this code, my X and Y are only simple variables, but not arrays.
If I use indexers, I get access only to one array:
public string this[int i]
{
set { this.myX[i] = value; }
get { return this.myX[i]; }
}
But how can I get access to second array?
Or I can't use property in this case? And I need only use:
public string[] myX;
public double[] myY;
An example with Tuples.
public class pointCollection
{
Tuple<String,Double>[] myPoints;
int maxArray;
int i;
public pointCollection(int maxArray)
{
this.maxArray = maxArray;
this.myPoints = new Tuple<String,Double>[maxArray];
}
public Tuple<String,Double> this[int i]
{
set { this.myPoints[i] = value; }
get { return this.myPoints[i]; }
}
}
And to access the points you do...
pointCollection pc = new pointCollection(10);
// add some data
String x = pc[4].Item1; // the first entry in a tuple is accessed via the Item1 property
Double y = pc[4].Item2; // the second entry in a tuple is accessed via the Item2 property
If I got it right, you need some kind or read/write-only wrapper for arrays to be exposed as properties.
public class ReadWriteOnlyArray<T>{
private T[] _array;
public ReadWriteOnlyArray(T[] array){
this._array = array;
}
public T this[int i]{
get { return _array[i]; }
set { _array[i] = value; }
}
}
public class pointCollection
{
string[] myX;
double[] myY;
int maxArray;
public ReadWriteOnlyArray<string> X {get; private set;}
public ReadWriteOnlyArray<double> Y {get; private set;}
public pointCollection(int maxArray)
{
this.maxArray = maxArray;
this.myX = new string[maxArray];
this.myY = new double[maxArray];
X = new ReadWriteOnlyArray<string>(myX);
Y = new ReadWriteOnlyArray<double>(myY);
}
}
and usage
var c = new pointCollection(100);
c.X[10] = "hello world";
c.Y[20] = c.Y[30] + c.Y[40];
The closest you'll come without either changing your data structure or moving to methods is to make a property that returns each array, much like you did in your first code block, except without the [i].
Then, you do var x = instanceOfPointCollection.MyX[someI]; for example.
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.
It seems that, due to an unknown cause, I am now unable to edit anything in my DataGridView. The DGV's ReadOnly property value is false, and all columns except for one all have the ReadOnly property set to false as well.
I'm beginning to think that it may be due to a special value I tried adding to one of my classes, one that I only wanted to be modified within the class, but still read only to the public. I don't think that value is messing with anything else, but none the less, here is the relevant portion of my code:
private void loaderWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
loadingBar.Value = e.ProgressPercentage;
if (e.UserState != null)
{
savefiles.Add((SaveFile)e.UserState);
}
}
Where savefiles is a BindingList, and where SaveFile is my class:
public class SaveFile
{
private string d_directory;
private int d_weirdnumber;
private bool d_isautosave;
private string d_fullname;
private string d_datatype;
private string d_owner;
private bool d_isquicksave;
private string d_title;
private string d_gametime;
public SaveFile() { }
public SaveFile(string directory, int weirdnumber, bool isautosave, string fullname, string datatype, string owner, bool isquicksave, string title)
{
d_directory = directory;
d_weirdnumber = weirdnumber;
d_isautosave = isautosave;
d_fullname = fullname;
d_datatype = datatype;
d_owner = owner;
d_isquicksave = isquicksave;
d_title = title;
}
public string Gametime
{
get { return d_gametime; }
}
public string Datatype
{
get { return d_datatype; }
set { d_datatype = value; }
}
public string Title
{
get { return d_title; }
set { d_title = value; }
}
public bool IsQuickSave
{
get { return d_isquicksave; }
set { d_isquicksave = value; }
}
public bool IsAutoSave
{
get { return d_isautosave; }
set { d_isautosave = value; }
}
public string Directory
{
get { return d_directory; }
set { d_directory = value; }
}
public string FullName
{
get { return d_fullname; }
set
{
d_fullname = value;
string[] split = value.Split(new char[]{'-'});
foreach (string str in split)
{
if (System.Text.RegularExpressions.Regex.IsMatch(str, "^\\d\\d:\\d\\d:\\d\\d$"))
{
d_gametime = str;
}
}
}
}
public int Weirdnumber
{
get { return d_weirdnumber; }
set { d_weirdnumber = value; }
}
public string Owner
{
get { return d_owner; }
set { d_owner = value; }
}
}
Gametime is that special property I mentioned earlier. It doesn't have a set function, but according to this, I should be in the clear, right?
Can anyone then tell me why I may not be able to edit any of the DGV cells?
EDIT: I just found out that not setting AutoGenerateColumns to false allows me to edit again, but I still don't know why.
After several hours, a friend finally took a look at it over Remote Desktop. He wrote a function to force all columns to have a non read-only status, and go figure, it worked. So we looked at the column properties in the editor, and somehow... I don't know why... they were all set to Read only. I swear I checked them 4 times before.
The lesson of this story (I guess): When in doubt, check your settings. When not in doubt, become doubtful. Otherwise, file a bug report to Microsoft :\