从bindingList获取属性值c#

时间:2015-08-15 08:05:23

标签: c# properties bindinglist

我在Class Restaurant中有绑定列表,我需要以Form1的形式调用,而不使用foreach来获取属性。如何在没有foreach的情况下访问属性。那可能吗?

这是我的代码:

   public static BindingList<MaterijaliGrid> GetMaterijali(DataGridView dataGridView1)
    {
        BindingList<MaterijaliGrid> materijali = new BindingList<MaterijaliGrid>();
        foreach (DataGridViewRow r in dataGridView1.Rows)
        {
            //while (materijali.Count < 50)
            //{
            materijali.Add(new MaterijaliGrid
            {
                Cosort = r.Cells[0].Value.ToString(),
                Model = r.Cells[1].Value.ToString(),
                Type = r.Cells[2].Value.ToString(),
                Color = r.Cells[3].Value.ToString(),
                Aantal = r.Cells[4].Value.ToString(),

                Unit = r.Cells[5].Value.ToString(),
                Component = r.Cells[6].Value.ToString(),
                Aantal2 = r.Cells[7].Value.ToString(),
                Unitcomp = r.Cells[8].Value.ToString(),
                Opis = r.Cells[9].Value.ToString(),
                Kleur = r.Cells[10].Value.ToString(),
                Soort = r.Cells[11].Value.ToString(),
                Price = r.Cells[12].Value.ToString(),
                Price1 = r.Cells[13].Value.ToString(),
                Price2 = r.Cells[14].Value.ToString(),
                // Oznaka = "MTK"
            });
        }
        //}
        return materijali;
    }

1 个答案:

答案 0 :(得分:1)

如果您想要更清晰的代码,我建议您将对象绑定到DataGridView中。然后,转换将很容易。像这样:

// Replace list of person with your MaterijaliGrid object
var list = new List<Person>();
list.Add(new Person { FirstName = "Robert", Initial = "Santos", LastName = "Lee" });
list.Add(new Person { FirstName = "Robert1", Initial = "Santos1", LastName = "Lee1" });
list.Add(new Person { FirstName = "Robert2", Initial = "Santos2", LastName = "Lee2" });
list.Add(new Person { FirstName = "Robert3", Initial = "Santos3", LastName = "Lee3" });

// You can hide row header if don't want it.  
dataGridView1.RowHeadersVisible = false;    
dataGridView1.AutoGenerateColumns = true;
dataGridView1.AutoSize = true;            
dataGridView1.DataSource = list;

现在你可以像这样轻松地投射它:

// Replace List and BindingList of person with your MaterijaliGrid object
var list = new List<Person>();
list.AddRange(dataGridView1.Rows
                           .Cast<DataGridViewRow>()
                           .Select(row => row.DataBoundItem as Person));

var bindingList = new BindingList<Person>(list);

人员类:

public class Person 
{
   // In case you don't want to display class property with there original names
   // you can annotate the property with DisplayName

   [DisplayName("First Name")]
   public string FirstName {get; set;}
   public string Initial {get; set;}
   public string LastName {get; set;}
}

示例输出:

enter image description here enter image description here