c# convert.ToInt not working? - c#

I have been trying to figure this out for an hour now and have tried parsing but hasnt worked. The code below keeps giving me the error Input string not in correct format on the two lines where i convert leagueData[2] and league data[3]. Am I missing something simple ?
public static void readLeagues(string theFile, ArrayList allLeagues)
{
StreamReader inLeagues = null;
bool anyMoreLeagues = false;
string[] leagueData = new string[frmLeagues.numLeagueItems];
string[] fixtureData = new string[frmLeagues.numFixItems];
Leagues tempLeague;
Fixtures tempFix;
int numFixInLeague, leaguePrize;
if (fileOpenForReadOK(theFile, ref inLeagues))
{
anyMoreLeagues = getNext(frmLeagues.numLeagueItems, inLeagues, leagueData);
while (anyMoreLeagues == true)
{
leaguePrize = Convert.ToInt32(leagueData[2]);
numFixInLeague = Convert.ToInt32(leagueData[3]);
tempLeague = new Leagues(leagueData[0], leagueData[1],numFixInLeague,
leaguePrize);
for (int i = 0; i < numFixInLeague; i++)
{
getNext(frmLeagues.numFixItems, inLeagues, fixtureData);
tempFix = new Fixtures(fixtureData[0], fixtureData[1], fixtureData[2]
, fixtureData[3], fixtureData[4]);
tempLeague.addFixturesToLeague(tempLeague.getLeagueFixtures(),tempFix);
}
allLeagues.Add(tempLeague);
anyMoreLeagues = getNext(frmLeagues.numLeagueItems, inLeagues, leagueData);
}
}
if (inLeagues != null) inLeagues.Close();
Below is the code for the League ClassThanks, Jack
class Leagues
{
private string LeagueName;
private string LeagueSponsor;
private int LeaguePrize;
private int LeagueNumFixtures;
ArrayList LeagueFixtures;
public Leagues(string inLeagueName, string inLeagueSponsor, int inLeaguePrize,
int inLeagueNumFixtures)
{
LeagueName = inLeagueName;
LeagueSponsor = inLeagueSponsor;
LeaguePrize = inLeaguePrize;
LeagueNumFixtures = inLeagueNumFixtures;
LeagueFixtures = new ArrayList();
}
public ArrayList addFixturesToLeague(ArrayList fixturesSoFar, Fixtures theNewFixture)
{
fixturesSoFar.Add(theNewFixture);
LeagueNumFixtures = fixturesSoFar.Count;
return fixturesSoFar;
}
public void setLeagueName(string inLeagueName)
{
LeagueName = inLeagueName;
}
public void setLeagueSponsor(string inLeagueSponsor)
{
LeagueSponsor = inLeagueSponsor;
}
public void setLeaguePrize(int inLeaguePrize)
{
LeaguePrize = inLeaguePrize;
}
public void setLeagueNumofFixture(int inLeagueNumFixtures)
{
LeagueNumFixtures = inLeagueNumFixtures;
}
public void setLeagueFixtures(ArrayList inLeagueFix)
{
LeagueFixtures = inLeagueFix;
}
public string getLeagueName()
{
return LeagueName;
}
public string getLeagueSponsor()
{
return LeagueSponsor;
}
public int getLeaguePrize()
{
return LeaguePrize;
}
public int getLeagueNumFixtures()
{
return LeagueNumFixtures;
}
public ArrayList getLeagueFixtures()
{
return LeagueFixtures;
}
}
}

I would make sure that leagueData[2] and leagueData[3] are not null, and then do a TryParse on them. You should also first check that leagueData is not null or empty. I'm assuming leagueData is an array of strings
var prize = leagueData[2];
int outNum;
int leaguePrize = Int.TryParse(prize, out outNum)? outNum : 0;
couple small edits per phoog's comment

Related

C# ComboBox List<object> ==> Show always the same object.name (multiple time)

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";
}

Compiling class in DLL and referencing it in another project in C#

Hope I'm asking this correctly.
I have this class:
class ListUtilities
{
private List<string> _datalist;
public ListUtilities(List<string> datalist)
{
_datalist = datalist;
}
//Method to calculate age from a date
private int getAge(string bdaystr)
{
DateTime today = DateTime.Today;
DateTime bday = new DateTime(Convert.ToInt32(bdaystr.Substring(0, 4)), Convert.ToInt32(bdaystr.Substring(4, 2)), Convert.ToInt32(bdaystr.Substring(6, 2)));
int age = today.Year - bday.Year;
if (bday > today.AddYears(-age)) age--;
return age;
}
//Method to print the data List
public void printDataList()
{
for (int i = 0; i < _datalist.Count; i++)
{
Console.WriteLine(_datalist.ElementAt(i));
}
}
//Method to calculate and print the ages
public void printAges()
{
List<int> ages = new List<int>();
for (int i = 0; i < _datalist.Count; i++)
{
string s = _datalist.ElementAt(i);
string[] data = s.Split(',');
ages.Add(getAge(data[3]));
}
Console.WriteLine("Ages:");
for (int i = 0; i < ages.Count; i++)
{
Console.WriteLine(ages.ElementAt(i));
}
}
//Method to search by surname
public string searchBySurname(string surname)
{
string res = "";
res = _datalist.Find(delegate(String str)
{
string[] data = str.Split(',');
string sname = data[1];
if (sname == surname)
return true;
else
return false;
});
return res;
}
//Method to search by phone number
public string searchByPhoneNumber(string phone)
{
string res = "";
res = _datalist.Find(delegate(String str)
{
string[] data = str.Split(',');
string phn = data[4];
if (phn == phone)
return true;
else
return false;
});
return res;
}
//Method to search by age
public string searchByAge(int age)
{
string res = "";
res = _datalist.Find(delegate(String str)
{
string[] data = str.Split(',');
int age2 = Convert.ToInt32(getAge(data[3]));
if (age2 == age)
return true;
else
return false;
});
return res;
}
//Method to sort by surname
public int sortBySurname(string x, string y)
{
string[] data_x = x.Split(',');
string sname_x = data_x[1];
string[] data_y = y.Split(',');
string sname_y = data_y[1];
return String.Compare(sname_x, sname_y);
}
//Method to sort by phone number
public int sortByPhoneNumber(string x, string y)
{
string[] data_x = x.Split(',');
int phn_x = Convert.ToInt32(data_x[4]);
string[] data_y = y.Split(',');
int phn_y = Convert.ToInt32(data_y[4]);
return phn_x.CompareTo(phn_y);
}
//Method to sort by age
public int sortByAge(string x, string y)
{
string[] data_x = x.Split(',');
int age_x = Convert.ToInt32(data_x[3]);
string[] data_y = y.Split(',');
int age_y = Convert.ToInt32(data_y[3]);
return age_y.CompareTo(age_x);
}
}
and I want to compile it in a .DLL file. I have tried doing it by the console like this:
csc /target:library /out:MathLibrary.DLL Add.cs Mult.cs
and putting that class in a Class Library project and building it, and I get the DLL file in both cases but the problem comes when I want to use that DLL.
I create a new Project, and I do reference the DLL file, but when I want to use it, this is the problem:
And, seems that there is nothing inside the DLL:
Best regards
class ListUtilities
By default classes are internal and can only be seen from inside the same assembly - make your class public and it should work fine:
public class ListUtilities
Your class needs to be public. By default classes are internal which means they can only be seen inside of the DDLL.
You need to make you class public
public class ListUtilities
as clases are by defualt internal.
On a side note:
You may try to use Visual Studio instead of Command Line which will make things easier for you.

object reference not set to an instance of an object

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.

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.

Umbraco 4.5.2 - Creating custom umbraco Data Editor Setting Types

I can't seem to find anything on how to edit the data editor settings before umbraco 6.2 (Juno). Is there any simple way, it must be possible. If you don't understand what i mean i want to do the same as http://www.nibble.be/?p=96 - just for umbraco 4.5.2.
Thanks :)
You need to make 3 classes Class 1 DataEditor
public class DataEditor : System.Web.UI.UpdatePanel, umbraco.interfaces.IDataEditor
{
public MWCropperDataEditor(umbraco.interfaces.IData Data, string Configuration)
{
_data = Data;
}
public virtual bool TreatAsRichTextEditor
{
get { return false; }
}
public bool ShowLabel
{
get { return true; }
}
public Control Editor { get { return this; } }
public void Save()
{
this._data.Value = "data;
}
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
imageUpload = new FileUpload();
imageUpload.ID = "imageUpload";
//shows Image
cropImage = new System.Web.UI.WebControls.Image();
cropImage.Width = width;
cropImage.Height = height;
cropImage.ImageUrl = this._data.Value.ToString();
//Shows dropdown
locationDropDown = new DropDownList();
AddItemsToDropDown();
lblInfo = new Label();
lblInfo.Attributes.Add("id", "title" + base.ClientID);
lblCropInfo = new Label();
lblCropInfo.Text = "Crop Location: ";
base.ContentTemplateContainer.Controls.Add(lblInfo);
base.ContentTemplateContainer.Controls.Add(imageUpload);
base.ContentTemplateContainer.Controls.Add(new LiteralControl("<br/>"));
base.ContentTemplateContainer.Controls.Add(new LiteralControl("<br/>"));
base.ContentTemplateContainer.Controls.Add(lblCropInfo);
base.ContentTemplateContainer.Controls.Add(locationDropDown);
base.ContentTemplateContainer.Controls.Add(new LiteralControl("<br/>"));
base.ContentTemplateContainer.Controls.Add(new LiteralControl("<br/>"));
base.ContentTemplateContainer.Controls.Add(cropImage);
}
}
class 2 DataType
public class MWCropperDataType : umbraco.cms.businesslogic.datatype.BaseDataType, umbraco.interfaces.IDataType
{
private umbraco.interfaces.IDataEditor _Editor;
private umbraco.interfaces.IData _baseData;
private MWCropperPrevalueEditor _prevalueeditor;
public override umbraco.interfaces.IDataEditor DataEditor
{
get
{
if (_Editor == null)
_Editor = new MWCropperDataEditor(Data, ((MWCropperPrevalueEditor)PrevalueEditor).Configuration);
return _Editor;
}
}
public override umbraco.interfaces.IData Data
{
get
{
if (_baseData == null)
_baseData = new umbraco.cms.businesslogic.datatype.DefaultData(this);
return _baseData;
}
}
public override Guid Id
{
get { return new Guid("71518B4E-B1A5-11DD-A22C-8AAA56D89593"); }
}
public override string DataTypeName
{
get { return "MWCropper"; }
}
public override umbraco.interfaces.IDataPrevalue PrevalueEditor
{
get
{
if (_prevalueeditor == null)
_prevalueeditor = new MWCropperPrevalueEditor(this);
return _prevalueeditor;
}
}
}
Class 3 PrevalueEditor
public class MWCropperPrevalueEditor : System.Web.UI.WebControls.PlaceHolder, umbraco.interfaces.IDataPrevalue
{
#region IDataPrevalue Members
// referenced datatype
private umbraco.cms.businesslogic.datatype.BaseDataType _datatype;
private TextBox _txtWidth;
private TextBox _txtHeight;
public MWCropperPrevalueEditor(umbraco.cms.businesslogic.datatype.BaseDataType DataType)
{
_datatype = DataType;
setupChildControls();
}
private void setupChildControls()
{
_txtWidth = new TextBox();
_txtWidth.ID = "txtWidth";
_txtWidth.CssClass = "umbEditorTextField";
Controls.Add(_txtWidth);
_txtHeight = new TextBox();
_txtHeight.ID = "txtHeight";
_txtHeight.CssClass = "umbEditorTextField";
Controls.Add(_txtHeight);
}
public Control Editor
{
get
{
return this;
}
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
if (!Page.IsPostBack)
{
if (Configuration.Length > 0)
{
string[] value = Configuration.Split(new char[]{';'});
_txtWidth.Text = value[0];
_txtHeight.Text = value[1];
}
else
{
_txtHeight.Text = "100";
_txtWidth.Text = "100";
}
}
}
public void Save()
{
_datatype.DBType = (umbraco.cms.businesslogic.datatype.DBTypes)Enum.Parse(typeof(umbraco.cms.businesslogic.datatype.DBTypes), DBTypes.Ntext.ToString(), true);
string data = _txtWidth.Text+";"+_txtHeight.Text;
SqlHelper.ExecuteNonQuery("delete from cmsDataTypePreValues where datatypenodeid = #dtdefid",
SqlHelper.CreateParameter("#dtdefid", _datatype.DataTypeDefinitionId));
SqlHelper.ExecuteNonQuery("insert into cmsDataTypePreValues (datatypenodeid,[value],sortorder,alias) values (#dtdefid,#value,0,'')",
SqlHelper.CreateParameter("#dtdefid", _datatype.DataTypeDefinitionId), SqlHelper.CreateParameter("#value", data));
}
protected override void Render(HtmlTextWriter writer)
{
writer.WriteLine("<table>");
writer.Write("<tr><th>Width:</th><td>");
_txtWidth.RenderControl(writer);
writer.Write("</td></tr>");
writer.Write("<tr><th>Height:</th><td>");
_txtHeight.RenderControl(writer);
writer.Write("</td></tr>");
writer.Write("</table>");
}
public string Configuration
{
get
{
object conf =
SqlHelper.ExecuteScalar<object>("select value from cmsDataTypePreValues where datatypenodeid = #datatypenodeid",
SqlHelper.CreateParameter("#datatypenodeid", _datatype.DataTypeDefinitionId));
if (conf != null)
return conf.ToString();
else
return "";
}
}
#endregion
public static ISqlHelper SqlHelper
{
get
{
return Application.SqlHelper;
}
}
}
I hope this can help you get started :)
Btw this also works for umbraco 6.2
Settings are called prevalues and you need a PrevalueEditor class that implements IDataPrevalue. Have a look at an example in this blog post:
http://www.eyecatch.no/blog/my-first-umbraco-datatype---part-2-rendering-a-recaptcha-control.aspx
This nibble post concerns doing a similar thing for v4.5 and prior, there is also a link within this for an even older version that I followed a while ago and found very helpful.
http://www.nibble.be/?p=62

Categories