再次问好;我需要在ListBoxes中显示X,Y,Risk。但我不能这样做。
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; }
}
答案 0 :(得分:1)
您必须将TrainingSet的实例化/创建移动到for循环中(您希望为添加到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);
}
否则,您将一遍又一遍地修改相同的TrainingSet实例。
答案 1 :(得分:1)
您也可以使用具有公共X,Y和风险的TrainingResult类
public class TrainingResult
{
public double X{get;set;}
public double Y{get;set;}
public string Risk {get;set};
}
并创建一个列表。接下来你可以像这样绑定它:
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();
这样做的好处是,您可以在x,y和风险之间建立更清晰的关系,并获得更具可读性(对我而言)的代码。缺点是当然DataMember是一个字符串值。