Reputation: 1411
I am new to programming in C#. I guess it might be a very easy solution which I am not aware of .
Suppose I have a class file
using System;
using System.Collections.Generic;
namespace sharepointproject1
{
public partial class School
{
public students[] students { get; set; }
}
public partial class student
{
public marks[] marks;
public extraactivites[] extraactivities;
}
public partial class marks
{
public int m1 { get; set; }
public int m2 { get; set; }
}
public partial class extraactivities
{
public decimal m5;
public decimal m6;
}
}
Now in aspx.cs file how do I add marks to the array declared?
namespace sharepointproject1
{
public partial class testing : usercontrol
{
School school = new school();
protected void Page_Load(object sender, EventArgs e)
{
school.students[0].marks[0].mark1 = 45;
}
}
}
I need to dynamically add items to it at run time. How do I do that? Do I have to change the array to list array in the class file..Hope I am making some sense out of my question.Later I need to bind the marks to the gridview.
Please help!
Upvotes: 0
Views: 2045
Reputation: 8488
Unless you're stuck for some reason in .NET 1.0 I'd strongly recommend looking at the Collection classes and then generics available in .NET. These will allow you to replace the array[] declarations with List where T is a .NET type. e.g
public class Student
{
public List<Mark> Marks{get;set;}
}
public class Mark
{
public int SomePropertyA { get; set; }
public int SomePropertyB { get; set; }
}
Upvotes: 0
Reputation: 3095
My advice is forget arrays and use List
or List<T>
which is the generic List.
Not only because solves the dynamic part of of your problem, but also has better performance avoiding box and unboxing.
Upvotes: 1
Reputation: 100527
You need to change Array to something that can grow dynamically like List<>. It may be better option to add methods like AddMark(marks mark) to student class and perform Add operation inside the class.
Upvotes: 0
Reputation: 1500155
Arrays have a fixed size - use a more flexible collection such as List<T>
, which will grow as you need it to.
Eric Lippert has a good blog post about why arrays should be considered somewhat harmful.
Additionally:
Upvotes: 6