Penguen
Penguen

Reputation: 17298

How to add list in ListBox?

Hello again; i need to show X,Y,Risk in ListBoxes. But i can not do it.

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            List<TrainigSet> listtraining = new List<TrainigSet>();
            TrainigSet tr = new TrainigSet();
            double[] X = { 2, 3, 3, 4, 5, 6, 7, 9, 11, 10 };
            double[] Y = { 4, 6, 4, 10, 8, 3, 9, 7, 7, 2 };
            string[] Risk = { "Kötü", "iyi", "iyi", "kötü", "kötü", "iyi", "iyi", "kötü", "kötü", "kötü" };
            for (int i = 0; i < X.Length; i++)
            {
                tr.X = X[i];
                tr.Y = Y[i];
                tr.Risk = Risk[i];
                listtraining.Add(tr);
            }
            for (int i = 0; i < listtraining.Count; i++)
            {
                ListBox1.Items.Add(listtraining[i].X.ToString());
                ListBox2.Items.Add(listtraining[i].Y.ToString());
                ListBox3.Items.Add(listtraining[i].Risk.ToString());
            }
        }
    }
}

public class TrainigSet
{
    public double X { get; set; }
    public double Y { get; set; }
    public string Risk { get; set; }
}

Upvotes: 1

Views: 6258

Answers (2)

Gluip
Gluip

Reputation: 2987

You could also use a TrainingResult class with a public X,Y, and Risk like this

public class TrainingResult
{
   public double X{get;set;}
   public double Y{get;set;}
   public string Risk {get;set};
}

And create a list of those. Next you could bind to it like this:

ListBoxX.DataSource = List<TrainingResult>
ListBoxX.DataMember = "X";
ListBoxX.DataBind();

ListBoxX.DataSource = List<TrainingResult>
ListBoxY.DataMember = "Y";
ListBoxY.DataBind();

ListBoxRisk.DataSource = List<TrainingResult>
ListBoxRisk.DataMember = "Risk";
ListBoxRisk.DataBind();

The advantage of this being that you have a more clear relation between x,y and risk and get more readable (to me) code. Disadvantage is offcourse the DataMember being a string value.

Upvotes: 1

M4N
M4N

Reputation: 96596

You have to move the instantiation/creation of the TrainingSet into the for loop (you want to create a new instance for every item you add to listtraining):

double[] X = { ... };
double[] Y = { ... };
string[] Risk = { ... };

for (int i = 0; i > X.Length; i++)
{
    TrainigSet tr = new TrainigSet(); // create a new TrainingSet
    ...
    listtraining.Add(tr);
}

Otherwise you will modify the same TrainingSet instance over and over again.

Upvotes: 1

Related Questions