How do I add a list to a ListBox?

Hi again; I need to show X, Y, Risk in ListBoxes. But I cannot do this.

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

      

+1


a source to share


2 answers


You need to move the creation / creation of the TrainingSet into the for loop (you want to create a new instance for each 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 be changing the same TrainingSet instance over and over.

+1


a source


You can also use TrainingResult class with 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 them. Then you can 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 is that you have a clearer connection between x, y and risk and get more readable (to me) code. The downside is that the DataMember is a string value.

+1


a source







All Articles