Can you enter data from a List to a combobox - c#

I have created a list within a class, following the same sort of lines as
public class Data
{
private int num;
private string text;
public Data()
{
}
public int Num
{
get { return num; }
set { num = value; }
}
public string Text
{
get { return text; }
set { text = value; }
}
static private List<Data> DataList = new List<Data>();
static public List<Data> GetList()
{
return DataList
}
and I bring up the list in other classes using
List<Data> DataList = Data.GetList();
does getting the list in another class allow you to add items to it?
and how would I add the items to a combobox?
EDIT: i am trying
LstList.Items.Add(DataList.Any(item => item.Num));
but I get the errors "cannot implicitly convert type int to bool"
and "A local variable named "Data" cannot be declared in this scope because it would give a different meaning to "Data""
EDIT: I have tried using .DataSource, but apparently it doesn't exist?

If I understand correctly, you are looking at adding new items to the static List in the above code from some other Class. If so, then no you cant do it. If you want to do it, expose a method called
public static void SetList(Data item_)
{
DataList.Add(item_);
}
Or make the List Public to be exposed to other classes
To your second point one assigns the data source of the comboBox to the List.
comboBox.DataSource= DataList;
This is an additional link that would help
How do I do bind list of custom objects to ComboBox?

You can bind the list as a DataSource
comboboxName.DataSource = Data.GetList();
comboboxName.ValueMember = "Num";
comboboxName.DisplayMember = "Text";

loop each data class from DataList and add the num property to the ListView Control
foreach(Data aData in DataList)
{
LstList.Items.Add(aData.Num.ToString()));
}

Related

what is an optimal way to approach this list to array problem

class ProjectGroup
{
private List<string> members = new List<string>();
public List<string> Members { get { return members; } }
}
class Course
{
public bool AddStudent(string name)
{
ProjectGroup projectGroup = new ProjectGroup();
projectGroup.Members.Add(name);
return true;
}
}
So in this code I created a private list of members and accessed it with a public list Members which makes no sense for being a private in the first place. So instead I made a clone of the private list ToArray().
class ProjectGroup
{
private List<string> members = new List<string>();
public string[] Members { get { return members.ToArray(); } }
}
but that means I can't use projectGroup.Members.Add(name); anymore since Members is an array now.
How can I add string name to projectGroup.Members now?
The first code makes perfect sense. It's a read-only property so you can get the List object in order to add items or whatever but you cannot set the property, so you cannot replace the existing List with a completely different one. The thing is, you don't need the field at all. Just use the property:
public List<string> Members { get; } = new List<string>();
There will be a field created implicitly by the compiler but you don't need to use it so you don't need to declare it explicitly.
but that means I can't use projectGroup.Members.Add(name); anymore since Members is an array now.
How can I add string name to projectGroup.Members now?
It depends, you should ask yourself, will this ProjectGroup.Members changed over time or only populated once at creation time? Is the encapsulation actually worth the trouble?
Populated Once
If it populated once, you can use constructor. This way you can ensure the members is read-only.
class ProjectGroup
{
private List<string> members;
public string[] Members { get { return members.ToArray(); } }
public ProjectGroup(List<string> projectMembers)
{
//Ensure projectMembers cant be null
if(projectMembers == null)
throw new ArgumentNullException("projectMembers");
members = projectMembers;
}
}
You can then create an instance of the ProjectGroup this way:
var pg = new ProjectGroup(new List<string>(){"robert", "bob"});
Restricting Operations
If you want to limit the number of action you can do on the List<string>, you can add methods to expose the functionality you required. For example, let's say we want to validate name before being added into the members. You can add a method in ProjectGroup to do so (lets call it AddName).
class ProjectGroup
{
private List<string> members = new List<string>();
public string[] Members { get { return members.ToArray(); } }
public void AddName(string name)
{
//Ensure name is never empty string or null
if(string.IsNullOrWhiteSpace(name))
throw new ArgumentNullException("name");
members.Add(name);
}
}
You can then add more members as such:
var pg = new ProjectGroup();
pg.AddName("alice");
pg.AddName("sarah");
You can create method for member removal in the similar fashion.

How to add value to an array of object in C#

I am consuming a third party web service and I want to add value to match the service reference class, and i am not sure how to add value to the following:
in reference:
public partial class UserInfor: object, System.ComponentModel.INotifyPropertyChanged
{
private ABC[] listOfABCField;
public ABC[] ListOfABC
{
get {
return this.listOfABCField;
}
set {
this.listOfABCField = value;
this.RaisePropertyChanged("ListOfABC");
}
}
}
public partial class ABC : object, System.ComponentModel.INotifyPropertyChanged
{
private string ipField;
private string fristNameField;
private string lastNameField;
}
//////////////////////////////////////////////////////
in my service.asmx file have tried to put value as below:
in below code i got exception in line ABC[] abc=new ABC[0]; error code:(NullReferenceException)
UserInfor user = new UserInfor();
ABC[] abc=new ABC[0];
abc[0].firstName= "petter";
abc[0].lastName = "lee";
user.ListOfABC = abc[1];
i also tried
in below code i got exception in line user.ListOfABC[0] = abc; error code:(NullReferenceException)
UserInfor user = new UserInfor();
ABC abc=new ABC[0];
abc.firstName= "petter";
abc.lastName = "lee";
user.ListOfABC[0] = abc;
any idea how to add abc to user class ? thank you in advance
This'll probably be easier if you use a List<> instead of an array. Change the property:
private List<ABC> listOfABCField;
public List<ABC> ListOfABC
{
// etc.
}
Don't forget to initialize it in the class' constructor so it's not null:
public UserInfor()
{
listOfABCField = new List<ABC>();
}
Then you can just add an object to it, which doesn't need any of the array syntax you were trying to use:
UserInfor user = new UserInfor();
ABC abc = new ABC();
abc.firstName= "petter";
abc.lastName = "lee";
user.ListOfABC.Add(abc);
You are doing it wrong, first instantiate the array, if you know in advance how many items it would contain then specify that as well in the square brackets like:
ABC[] abc=new ABC[1]; // this array will contain 1 item maximum
now instantiate that item and then set values of properties :
abc[0] = new ABC(); // instantiating first item of array which is at 0th index
abc[0].firstName= "petter";
abc[0].lastName = "lee";
If you don't know how many item would come in it, then go with #David's suggestion of using List<T>

Designing class with fields as string arrays

I'm not sure if this is the right title, but here goes.
I have a simple class with many fields and a method that checks these fields. The class looks like below. I removed the accessors for space.
So I call SetAlarms to set the fields to later use them with method AlarmsOk() and other methods. Everything worked fine since the datatable only had one row.
Now the datatable has two rows. So I was thinking of using a struct array to store these two rows. If I continued using the class fields, I'd set them as arrays I would need to initialize each string, which means that I would need to add 100 rows, one per field. One the other hand, I can have a struct array and initialize it two length of 2 with one line.
Is this correct?
public class Alarms
{
private string[] alarm0;
private string[] alarm1;
// to Alarm99
private string[] alarm99;
public void SetAlarms(DataTable AlarmsTable)
{
int currentRow = 0;
int rowCount = AlarmsTable.Rows.Count; //AlarmsTable has 2 rows
alarm0 = new string[rowCount];
alarm1 = new string[rowCount];
// to Alarm99
alarm99 = new string[rowCount];
foreach (DataRow row in AlarmsTable.Rows)
alarm0[currentRow] = Convert.ToString(AlarmsTable.Rows[currentRow]["Alarm0"]);
alarm1[currentRow] = Convert.ToString(AlarmsTable.Rows[currentRow]["Alarm1"]);
// to Alarm99
alarm99[currentRow] = Convert.ToString(AlarmsTable.Rows[currentRow]["Alarm99"]);
currentRow++;
}
}
public bool AlarmsOk()
{
//Check if alarms are OK, return true/false
}
}
If I understand correctly, I would rather use some AlarmData class and a List instead:
public class AlarmData
{
public string Alarm0 { get; set; }
...
public string Alarm99 { get; set; }
}
public class Alarms
{
private List<AlarmData> alarmData = new List<AlarmData>();
public void SetAlarms(DataTable AlarmsTable)
{
this.alarmData.Clear();
foreach (DataRow row in AlarmsTable.Rows)
{
var newData = new AlarmData();
newData.Alarm0 = Convert.ToString(AlarmsTable.Rows[currentRow]["Alarm0"]);
...
newData.Alarm99 = Convert.ToString(AlarmsTable.Rows[currentRow]["Alarm99"]);
this.alarmData.Add(newData);
}
}
public bool AlarmsOk()
{
//Check if alarms are OK, return true/false
}
}
So you have a class that correspond to your table (and an instance in your list for each row), which is easier to read IMO.
You can use array of arrays:
private string[][] alarm;
And use it:
alarm[0][currentRow] = value;
This seems like bad design to me. Your OP suggests you are crowbarring everything into a single table.
Rather than have a single Alarms class,I think you should have a singular Alarm class. This would store information about a single alarm entity only. Then whatever the object is that actually has the alarms (say a Foo) would have a collection of Alarm objects - so something like
public class Foo
{
public List<Alarm> Alarms { get; set; }
}
On the database side you would have a Foo table and an Alarm table. Your Alarm table will have a FooID column so you can link each one back to the Foo.

C# - Set array size

I'm trying to create a new class which contains an array but the size of it shouldn't be constant.
Let's say I have the Program.cs and I have a different class called Category.cs.
Category.cs looks like this:
class Category
{
static int MemberCount = 2;
private string[] ids = new string[MemberCount];
public string[] Ids
{
get { return ids; }
set { ids = value; }
}
...
My goal is to somehow modify MemberCount when I create a new object from this Class...
I hope it make sense...
Thank you! :-)
Assuming you actually want/need to use an array with the length fixed at object construction time (as opposed to say the List<T> wisely suggested in comments), you can add a constructor:
class Category
{
private readonly string[] ids;
public string[] Ids
{
get { return ids; }
}
public Category(int memberCount) {
ids = new string[memberCount];
}
}
Note that I have removed the setter on the Ids property as otherwise the array can be overwritten with one of an arbitrary length. Likewise I have made ids readonly.
Use a generic list or other collection class.
class Category
{
public List<string> Ids { get; set; }
Category()
{
Ids = new List<string>();
}
}
You can resize your array using this method:
Array.Resize(ref ids, newSizeOfArray);

Inheritance. Polymorphism. Abstractization

I'm working on a testing platform app for students. Since the question can have one or multiple correct answers, I need radio buttons/checkboxes for selecting the right one(s). I would like to implement an abstract class with an Add method. From it, derive two classes, each of them containing an array of RaddioButtons or Checkboxes. Is there a better way to do this than the one listed below? I mean, can the add method be put in the abstract class?
public class AnswerForm
{
public static int no;
public AnswerForm()
{
no=0;
}
}
public class RadioButtonClass:AnswerForm
{
RadioButton[] vector;
public void Add(RadioButton rbutton)
{
vector[no++] = rbutton;
}
}
public class CheckBoxClass : AnswerForm
{
CheckBox[] vector;
public void Add(CheckBox cbox)
{
vector[no++] = cbox;
}
}
I also have two vectors in which I put a fixed number of elements, RadioButtons and Checkboxes. These elements exist in the Windows Form Form1.cs[design]. What I would like to do is pass one an element of type AnswerForm to a function and in the function, based on what type of question I have, allocate memory to my AnswerForm object for one of the derived classes. Also, it might be easier if the Add method would have as parameter a s string, and vector[no++].Text=s;
The prototype of the function:
public void readQuestions(RichTextBox richTextBox, AnswerForm answerForm)
Here I'm parsing an XML file and put the objects in a List. The XML contains Questions, each having a type(multiple or single answer), the text which goes to the richTextBox, and the answers. Next i'm looping through the question list and check question's type. If multiple answers, then put each answer in a CheckBox.Text. Else, put it in a RadioButton.Text. Before assigning the text to each WinForm element, I would like to allocate the corresponding object type(RadioButtonClass or CheckBoxClass) and then use the add method for each answer of the current question. That is why I thought of inheritance, abstractization an polymorphism.
This is how it look like now:
public void readQuestions(RichTextBox richTextBox, AnswerForm answerForm)
{
var file = XDocument.Load("QuestionsTest.xml");
var subject = new Subject();
subject.Name = (string)file.Root.Attribute("Subject");
var questions = from question in file.Root.Elements("Question")
select new Question
{
NumberOfCorrectAnswers=(int)question.Attribute("NumberOfAnswers"),
Text = (string)question.Element("Text"),
Answers = new List<Answer>(
from answers in question.Element("Answers").Elements("Answer")
select new Answer
{
Text = (string)answers
})
};
using (var db = new TestingPlatformContext())
{
db.Subjects.Add(subject);
foreach (var question in questions)
{
//Console.WriteLine("Subject: {0}\n Text: {1}", question.Subject, question.Text);
richTextBox.Text = question.Text;
//db.Questions.Add(question);
foreach (var answer in question.Answers)
//Console.WriteLine("Answer: {0}", answer.Text);
if (question.NumberOfCorrectAnswers != 1)
{
answerForm = new CheckBoxClass();
answerForm.Add(answer.Text);
//db.Answers.Add(answer);
}
else
{
answerForm = new RadioButtonClass();
answerForm.Add(answer.Text);
}
}
}
}
Yes, you can move the Add() method to parent class, using generic:
public class AnswerForm<T>
{
private readonly IList<T> _list;
public AnswerForm()
{
_list = new List<T>();
}
public void Add(T button)
{
_list.Add(button);
}
}
public class RadioButtonClass:AnswerForm<RadioButton>
{
}
public class CheckBoxClass : AnswerForm<CheckBox>
{
}
I made a few changes:
- Use list instead of array, it's more flexible in this case
- Use generic in parent class AnswerForm
A solution, much simple, would be like this:
public class AnswerForm
{
public static int no;
private RadioButton[] rbuttons;
private Checkbox[] checkboxes;
public AnswerForm()
{
no=0;
rbuttons = new RadioButton[]
{
radioButton1,radioButton2,radioButton3,radioButton4,radioButton5
};
checkboxes = new CheckBox[]
{
checkBox1,checkBox2,checkBox3,checkBox4,checkBox5,checkBox6
};
}
public void AddRadio(string s)
{
rbuttons[no++].Text=s;
}
public void AddBox(string s)
{
checkboxes[no++].Text=s;
}
}
But this is far from elegant.

Categories

Resources