如何从Property Grid获取所有单元格值c#

时间:2013-11-13 07:21:17

标签: c# datagridview propertygrid

我有一个属性Grid如下:

enter image description here

我想在点击提交按钮时将属性网格的完整内容复制到数据网格视图(dataGeriView1)。

怎么做? 请帮忙。

2 个答案:

答案 0 :(得分:1)

 private void Submit_Click(object sender, EventArgs e)
    {
        //propertyGrid1.SelectedObject = this;
        dataGridView1.Columns.Add("Property", "Property");
        dataGridView1.Columns.Add("Value", "Value");
        GridItem gi = propertyGrid1.SelectedGridItem;

        while (gi.Parent != null)            
            gi = gi.Parent;

        foreach (GridItem item in gi.GridItems)            
            ParseGridItems(item); //recursive

        dataGridView1.Sort(dataGridView1.Columns["Property"], ListSortDirection.Ascending);

    }
    private void ParseGridItems(GridItem gi)
    {
        if (gi.GridItemType == GridItemType.Category)            
            foreach (GridItem item in gi.GridItems)                
                ParseGridItems(item);                

        dataGridView1.Rows.Add(gi.Label, gi.Value);

    }

改编自https://stackoverflow.com/a/12109186/1163434

答案 1 :(得分:0)

以下是我为解决上述问题而创建的示例代码段。通过添加列名称,年龄,电子邮件,电话创建DataGridview

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }
    private void Form1_Load(object sender, EventArgs e)
    {
      Student std = new Student {Name = "Vimal" , Phone = "PhoneValue", Email="mymail",Age=24};
      propertyGrid1.SelectedObject= std;
    }

    private void button1_Click(object sender, EventArgs e)
    {
        int index = dataGridView1.Rows.Count - 1;
        Student std = (Student)propertyGrid1.SelectedObject;
        dataGridView1.Rows[index].Cells["Name"].Value = std.Name;
        dataGridView1.Rows[index].Cells["Age"].Value = std.Age;
        dataGridView1.Rows[index].Cells["Email"].Value = std.Email;
        dataGridView1.Rows[index].Cells["Phone"].Value = std.Phone;
    }
}

public class Student
{
    public int Age { get; set; }
    public string Email { get; set; }
    public string Name { get; set; }
    public string Phone { get; set; }
}