[英]update a generic List Item using C#
在查看了此处发布的所有问题后,我无法弄清楚如何更新通用列表中的一项,对此我深表歉意。 这是我的问题:
我有这个结构:
List<LineInfo> Lines = new List<LineInfo>();
LineInfo LInfo;
struct LineInfo
{
public int line;
public int WO;
public string Brand;
public string Model;
public string Customer;
public int Qty;
public int Target;
public string Leader;
public string Start;
public string End;
public int Percent;
}
我想更新输入的 LInfo 项目之一的“百分比”字段,我有当前的 position (aCurrentLine)。
LInfo.Percent = Convert.ToInt32((RealProduced / DesireProd) * 100);
Lines[aCurrentLine]....?
请指教,谢谢。
只是
LInfo.Percent = Convert.ToInt32((RealProduced / DesireProd) * 100);
Lines[aCurrentLine] = LInfo;
应该工作......但请不要使用公共字段或可变结构。 两者在可维护性和意外影响方面都很糟糕。
您在 C# 中创建的大多数类型都可能是类 - 您想要创建值类型(结构)的情况相对较少。 您应该确保了解两者之间的差异。
同样,C# 中的字段应该几乎总是私有的。 它们应该是该类型的实现细节,而不是其公共 API 的一部分。 改用属性- C# 3 中的自动实现属性使这些几乎像字段一样紧凑,如果您只想要一个微不足道的属性。
我只有一个 adivice。可变结构是邪恶的。 尽量避免它。
Lines[aCurrentLine] = LInfo;
您将无法访问Lines[aCurrentLine].Percent
因为它只是更新一个临时副本。
使用网格视图更新通用列表记录。只需输入此代码。
List<Address> people = (List<Address>)Session["People"];
people[e.RowIndex].DoorNo = ((TextBox)grdShow.Rows[e.RowIndex].Cells[2].Controls[0]).Text;
people[e.RowIndex].StreetName = ((TextBox)grdShow.Rows[e.RowIndex].Cells[3].Controls[0]).Text;
people[e.RowIndex].City = ((TextBox)grdShow.Rows[e.RowIndex].Cells[4].Controls[0]).Text;
people[e.RowIndex].PhoneNo = ((TextBox)grdShow.Rows[e.RowIndex].Cells[5].Controls[0]).Text;
grdShow.EditIndex = -1;
grdShow.DataSource = people;
grdShow.DataBind();
并将此代码放入页面加载事件。
if (!IsPostBack)
{
List<Address> people = new List<Address>();
Session["People"] = people;
}
使用网格视图创建通用列表在按钮事件上编写此代码(它从文本框中获取数据并保存在列表中)
GenerateList();//call the method GenerateList();
GenerateList() 的语法;
private void GenerateList()
{
if (Session["People"] != null)
{
List<Address> people = (List<Address>)Session["People"];
Address a1 = new Address();
a1.DoorNo = txtDoorno.Text;
a1.StreetName = txtStreetName.Text;
a1.City = txtCityname.Text;
a1.PhoneNo = txtPhoneno.Text;
people.Add(a1);
Session["People"] = people;
grdShow.DataSource = people;
grdShow.DataBind();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.