I'm trying to access a List within an ArrayList to bind that list to a listbox.
Here is the code for my driver class.
public class Driver
{
private string name;
private string occupation;
private DateTime dateOfBirth;
private List<DateTime> dateOfClaim;
public Driver(string name, string occupation, DateTime dateOfBirth, List<DateTime> dateOfClaim)
{
this.name = name;
this.occupation = occupation;
this.dateOfBirth = dateOfBirth;
this.dateOfClaim = new List<DateTime>();
}
public string driverName
{
get{ return name; }
set{ name = value; }
}
public string driverOccupation
{
get { return occupation; }
set { occupation = value; }
}
public DateTime driverDateOfBirth
{
get { return dateOfBirth; }
set { dateOfBirth = value; }
}
public List<DateTime> driverDateOfClaim
{
get { return dateOfClaim; }
set { dateOfClaim = value; }
}
}
I have a button which allows you to add a date for a claim to a driver, up to a maximum of 5 claims so I have a temporary list which holds the dates list before it is assigned to the list in the arraylist as the new driver has not yet been created in the arraylist.
Here are parts of the code from a form which declares and populates the arraylist.
private ArrayList drivers = new ArrayList();
private List<DateTime> claimDates = new List<DateTime>();
if (noOfClaims <= 4)
{
claimDates.Add(dtpAddClaim.Value.Date);
noOfClaims++;
}
if (noOfDrivers <= 4)
{
drivers.Add(new Driver(txtName.Text, txtOccupation.Text, dtpDOB.Value.Date, claimDates));
noOfDrivers++;
}
So my problem comes when trying to access the dateOfClaim list.
I'm trying to bind that list to a listbox and have tried using this to do that but am getting an error saying 'ArrayList' does not contain a definition for 'driverDateOfClaim'.
lbxClaimDates.DataSource = drivers.driverDateOfClaim;
Any help solving this would be greatly appreciated.
You need to index the array list. You would need to access an item of the array list and then acces driverDateOfClaim for a specific Driver instance in the ArrayList
lbxClaimDates.DataSource = ((Driver) drivers[0]).driverDateOfClaim
Also in Drivers constructor you arent assigning the dateOfClaim parameter to the DateOfClaim property.
Related
I am coding an application for my study, but i'm stuck at this point. I made a class called 'Neighborhood'. This class has a string and an int. In my main code I give the class a value and put it in a list. I now want to loop through my list and get the int out of it (put it in a listbox, or do a calculation). How do I get the int out of the list?
class Wijk
{
private string wijken;
private int tijd;
public string Wijken
{
get { return wijken; }
set { wijken = value; }
}
public int Tijd
{
get { return tijd; }
set { tijd = value; }
}
}
Created the list and the instance of the class.
List<object> Uden = new List<object>();
Wijk Wijkeninput = new Wijk();
Now I value the string and int with a combobox and textbox.
private void wijkAanmaken()
{
Wijkeninput.Wijken = Convert.ToString(cbWijken);
Wijkeninput.Tijd = Convert.ToInt16(tbSnelheid.Text);
Uden.Add(Wijkeninput);
}
For this, instead of having an object list, you can have list containing class objects like
List<Wjik> Uden = new List<Wjik>();
then you can access int as follows:
foreach (Wjik obj in listProgram)
{
int tij = Convert.ToInt32(obj.tijd);
}
First the List can be declared like this:
List<Wijk> Uden = new List<Wijk>();
To iterate over it:
foreach(var item in Uden)
{
var myInt = item.Tijd;
var myString = item.Wijken;
//here do whatever you want with the values
}
i am working with a .net application where i have a web service that returns values in array form and now this array values i want to pass to a class and also as a reference to a private object. But since i am fresh new in programming i do not know how where an with what logic to start.
This is the private obj i created and i want to pass those references where CT is the array type and clsIn is the info that comes from another class but i have no idea how to pass neither of them.
private object TotInfo(clsIn In, CT ct)
{
TotInfo objFromCD = new TotInfo();
return objFromCD;
}
And here is the new class i have created that where i want to pass all the values from clsIn and CT:
public class TotInfo
{
// Object properties
private string LAST_OFFER;
private string LAST_OFFER_DATE;
private string CLOSING_REASON;
private string _NO;
private string _STATUS;
#region "GET/SET Property"
public string NO
{
get { return _NO; }
set { _NO = value; }
}
public string LAST_OFFER
{
get { return _LAST_OFFER; }
set { _LAST_OFFER = value; }
}
public string LAST_OFFER_DATE
{
get { return _LAST_OFFER_DATE; }
set { _LAST_OFFER_DATE = value; }
}
public string CLOSING_REASON
{
get { return _CLOSING_REASON; }
set { _CLOSING_REASON = value; }
}
public string STATUS
{
get { return _STATUS; }
set { _STATUS = value; }
}
#endregion
#region "Costruttori"
public CardsTotInfo() { }
public CardsTotInfo(string No, string lastOffer, string lastOfferDate, string closingReason, string status)
{
this.NO = No;
this.LAST_OFFER = lastOffer.ToUpper();
this.LAST_OFFER_DATE = lastOfferDate.ToUpper();
this.CLOSING_REASON = closingReason.ToUpper();
this.STATUS = status.ToUpper();
}
}
I have passed, or better say i think i have passed in the correct way the values of clsIn but i do not know how to pass the properties of the array type CT[].
I really need help.
Thank you in advance.
If CT is an object array and the data you get from the web service always comes in the same order, for instance using an arbitrary example:
object[] CT = { 1, DateTime.Now, "foo", true }
If you know that each property data inside the array will always be at the same index (you will always have a int in index 0 representing an Id, and a DateTime on index 1 representing the last offer day and so on)
I would say you need to set each property "manually":
private object TotInfo(clsIn In, CT ct)
{
TotInfo objFromCD = new TotInfo();
//get data from DB
//set the data from the array into the class properties
objFromCD.Id = (int)ct[0];
objFromCD.LastOfferDate = (DateTime)ct[1];
objFromCD.ClosingReason = (string)ct[2];
objFromCD.Available = (bool)ct[3];
return objFromCD;
}
I'm trying to display dates from a list within a ListBox. To do this I am trying to bind the list to a listbox.
Here is the code for my driver class.
public class Driver
{
private string name;
private string occupation;
private DateTime dateOfBirth;
private List<DateTime> dateOfClaim;
public Driver(string name, string occupation, DateTime dateOfBirth, List<DateTime> dateOfClaim)
{
this.name = name;
this.occupation = occupation;
this.dateOfBirth = dateOfBirth;
this.dateOfClaim = dateOfClaim;
}
public string DriverName
{
get{ return name; }
set{ name = value; }
}
public string DriverOccupation
{
get { return occupation; }
set { occupation = value; }
}
public DateTime DriverDateOfBirth
{
get { return dateOfBirth; }
set { dateOfBirth = value; }
}
public List<DateTime> DriverDateOfClaim
{
get { return dateOfClaim; }
set { dateOfClaim = value; }
}
}
I have a button which allows you to add a date for a claim to a driver, up to a maximum of 5 claims. I have a 'temporary' list which holds these dates before they are assigned to the dateOfClaim list within the Driver list as the new driver object has not yet been created.
Here are parts of the code from a form which declares and populates the arraylist.
private List<Driver> drivers = new List<Driver>();
private List<DateTime> claimDates = new List<DateTime>();
if (noOfClaims <= 4)
{
claimDates.Add(dtpAddClaim.Value.Date);
noOfClaims++;
}
if (noOfDrivers <= 4)
{
drivers.Add(new Driver(txtName.Text, txtOccupation.Text, dtpDOB.Value.Date, claimDates));
noOfDrivers++;
}
To bind the dateOfClaim list to the listbox I have tried using the following code, but nothing displays in the listbox.
lstClaimDates.DataSource = drivers;
lstClaimDates.DisplayMember = "DriverDateOfClaim";
I've tried displaying the dates in a label using the following code, but again, nothing displays which leads me to believe I'm not adding to the dateOfClaim list correctly.
foreach (DateTime d in drivers[0].driverDateOfClaim)
label1.Text += d.ToString() + " ";
Any help solving this would be greatly appreciated.
WinForms:
You need to define the value/field/property that you would like to show in your listBox:
List<Driver> drivers = new List<Driver>();
drivers.Add(new Driver("name", "The Earth", DateTime.Now, null));
listBox1.DataSource = drivers;
listBox1.DisplayMember = "drivername";
Update 0:
Let me know if it is not applicable for you:
foreach (var c in drivers[0].driverDateOfClaim)
{
listBox1.Items.Add(c);
}
Magnus Montin is superprogrammer and he shows another solution:
List<Driver> drivers = new List<Driver>();
drivers.Add(new Driver("name", "The Earth", DateTime.Now, new List<DateTime>() {
DateTime.Now,
DateTime.Now,
} ));
listBox1.DataSource = drivers[0].driverDateOfClaim;
Update 1:
List<Driver> drivers = new List<Driver>();
drivers.Add(new Driver("name", "The Earth", DateTime.Now, new List<DateTime>()
{
DateTime.Now,
DateTime.Now,
} ));
foreach (var c in drivers[0].driverDateOfClaim)
{
textBox1.Text += " | " + c;
}
you can bound them as string, e.g. using Linq
lstClaimDates.DataSource = drivers[i].driverDateOfClaim.Select(d => d.ToString()).ToList();
should do the job (you can specify your date format in the ToString call)
I'm trying to add strings to a List<string> so I can print them with a loop in a certain point of time, being more specific here is part of my code:
public class Foo{
public string propertyA;
public string propertyB;
public string propertyC;
public List<string> list;
Public Foo(){
list = new List<string>();
list.Add(propertyA);
list.Add(propertyB);
list.Add(propertyC);
}
}
In later code, after assigning propertyA and the other variables and trying to iterate over the List I get empty strings. I require the properties to be in the list. My questions is which would be the best way to achieve this?
Looks like you are getting empty strings because when you are adding to the list the values in your properties have not been set at the time that the Foo() constructor is called...
Try passing values and setting them in the Foo constructor as follows:
public class Foo{
public string propertyA;
public string propertyB;
public string propertyC;
public List<string> list;
Public Foo(string propA, string propB, string propC){
propertyA = propA;
propertyB = propB;
propertyC = propC;
list = new List<string>();
list.Add(propertyA);
list.Add(propertyB);
list.Add(propertyC);
}
}
Alternatively you could add the values to the list at a later time when the properties are actually set and not in the constructor e.g.
public string PropertyA
{
//set the person name
set { propertyA = value;
list.Add(value);
}
//get the person name
get { return propertyA; }
}
...
What you're seeing is expected behavior. Updating "propertyA", etc later on won't update the strings that have already been added to the collection.
You could consider using a Dictionary instead of your own class, and then adding and updating elements is easier: (and you don't have to keep updating your class with new property names)
var properties = new Dictionary<string, string>();
properties.Add("propertyA", "some value of property A");
properties["propertyA"] = "some new value";
And when you want to display the values later:
MessageBox.Show(string.Join(Environment.NewLine, properties));
Alternatively, if you want a class and the option of adding properties to it, then maybe extending the Dictionary class like this will at least make things easier to maintain, so you can add more properties that'll stay in sync with the underlying Dictionary, with a minimum of fuss.
public class PropertyCollection : Dictionary<string, string>
{
public string PropertyA
{
get { return GetValue(); }
set { StoreValue(value); }
}
public string PropertyB
{
get { return GetValue(); }
set { StoreValue(value); }
}
protected string GetValue([CallerMemberName] string propName = "")
{
if (ContainsKey(propName))
return this[propName];
return "";
}
protected void StoreValue(string propValue, [CallerMemberName] string propName = "")
{
if (ContainsKey(propName))
this[propName] = propValue;
else
Add(propName, propValue);
}
}
If you want to assign propertyA, B, C after an instance of Foo is created and enumerate them, you could try something like this:
public class Foo
{
public string propertyA { get { return list[0]; } set { list[0] = value; } }
public string propertyB { get { return list[1]; } set { list[1] = value; } }
public string propertyC { get { return list[2]; } set { list[2] = value; } }
public List<string> list = new List<string>() {"", "", ""};
}
For the reasons why the code behaves in a way you might not expect, see How are strings passed in .NET?
I have a List that contains a series of transaction objects. What I'm trying to do is to display these transaction objects in a Datagridview control on loading a form, basically the Datagridview should represent something of a transaction register to display the data for each of the transaction objects in the list.
I must admit to a lack of experience when it comes to using Datagridviews and I'm having some difficulty with understanding what I need to do here.
My question is, how do I go about getting the details of each of the objects in the list to display in the Datagridview?
Here is my code.
First the transaction class:
public class Transaction
{
// Class properties
private decimal amount;
private string type;
private decimal balance;
private string date;
private string transNum;
private string description;
// Constructor to create transaction object with values set.
public Transaction(decimal amount, string type, decimal currBal, string date, string num, string descrip)
{
this.amount = amount;
this.type = type;
this.balance = currBal;
this.date = date;
this.transNum = num;
this.description = descrip;
}
// Get and Set accessors to allow manipulation of values.
public decimal Amount
{
get
{
return amount;
}
set
{
amount = value;
}
}
public string Type
{
get
{
return type;
}
set
{
type = value;
}
}
public decimal Balance
{
get
{
return balance;
}
set
{
balance = value;
}
}
public string Date
{
get
{
return date;
}
set
{
date = value;
}
}
public string TransNum
{
get
{
return transNum;
}
set
{
transNum = value;
}
}
public string Description
{
get
{
return description;
}
set
{
description = value;
}
}
public decimal addCredit(decimal balance, decimal credit)
{
decimal newBalance;
newBalance = balance + credit;
return newBalance;
}
public decimal subtractDebit(decimal balance, decimal debit)
{
decimal newBalance;
newBalance = balance - debit;
return newBalance;
}
}
}
Now the code for the "Register" form:
public partial class Register : Form
{
List<Transaction> tranList = new List<Transaction>();
public Register(List<Transaction> List)
{
InitializeComponent();
this.tranList = List;
}
private void Register_Load(object sender, System.EventArgs e)
{
//regView represents the Datagridview that I'm trying to work with
regView.AutoSize = true;
regView.DataSource = tranList;
regView.Rows.Add(tranList[0]);
}
}
And here's the output I get.
There's really two high level approaches to this.
1) Add the manually created rows directly to the DataGridView. In this case, you have to manually update/remove them as things change. This approach is "ok" if you don't intend to alter/change the content of the display after you initialize it. It becomes untenable if you do.
To add it directly, you need to create a DataGridViewRow, and populate it with the individual values, and then add the DataGridViewRow to the DataGridView.Rows.
2) Data bind the DGV. There's many articles about databinding to a DataGridView. In some cases, it's easier to just add your data to a DataTable, and then extract a DataView from that, and bind the DataGridView to the DataView. Other people find it easier to directly bind to a collection.
CodeProject has a decent article to get you started down that path, but a quick Google search will yield many other articles.
http://www.codeproject.com/Articles/24656/A-Detailed-Data-Binding-Tutorial
use as DGV:
DataGridView groupListDataGridView;
column:
DataGridViewTextBoxColumn groupListNameColumn;
column setup should be like this:
groupListNameColumn.DataPropertyName = "name";
use this property, else all columns will be added.
groupListDataGridView.AutoGenerateColumns = false;
populate like this:
private void populateGroupList() {
groupListDataGridView.DataSource = null;
formattedGroupList = new SortableBindingList<DataGridGroupObject>();
foreach (GroupObject go in StartUp.GroupList) {
DataGridGroupObject dggo = new DataGridGroupObject();
dggo.id = go.Id;
dggo.name = go.Name;
formattedGroupList.Add(dggo);
}
groupListDataGridView.DataSource = formattedGroupList;
groupListDataGridView.Invalidate();
}
and model:
public class DataGridGroupObject
{
public int id { get; set; } //this will be match id column
public string name { get; set; } // this will be match name column
}
Simply add using System.Linq; at the top. Then you can do this:
//This will create a custom datasource for the DataGridView.
var transactionsDataSource = tranList.Select(x => new
{
Amount = x.amount,
Type = x.type,
Balance = x.balance,
Date = x.date,
TransNum = x.transNum
Description = x.description
}).ToList();
//This will assign the datasource. All the columns you listed will show up, and every row
//of data in the list will populate into the DataGridView.
regView.DataSource = transactionsDataSource;