使用C#更新通用列表项

时间:2011-08-17 14:08:08

标签: c# list

在查看了此处发布的所有问题后,我无法弄清楚如何更新通用列表的项目,对不起。这是我的问题:

我有这个结构:

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项目的字段“百分比”,我有当前位置(aCurrentLine)。

LInfo.Percent = Convert.ToInt32((RealProduced / DesireProd) * 100);                 
Lines[aCurrentLine]....?

请指教,谢谢。

3 个答案:

答案 0 :(得分:3)

只需

LInfo.Percent = Convert.ToInt32((RealProduced / DesireProd) * 100);
Lines[aCurrentLine] = LInfo;

应该有效......但不要使用公共字段可变结构。两者在可维护性和意外影响方面都很糟糕。

您在C#中创建的大多数类型可能都是类 - 您需要创建值类型(struct)的情况相对较少。您应该确保知道differences between the two

同样,C#中的字段几乎总是是私有的。它们应该是该类型的实现细节,而不是其公共API的一部分。 Use properties instead - 如果您只想要一个简单的属性,C#3中自动实现的属性使得这些属性几乎与字段一样紧凑。

答案 1 :(得分:1)

我只有一个建议。可变结构是邪恶的。尽量避免它。

Lines[aCurrentLine] = LInfo;

您无法访问Lines[aCurrentLine].Percent,因为它只更新临时副本。

答案 2 :(得分:0)

用于通过网格视图更新通用列表记录。只需输入此代码。

 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()的sytex;

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