加载对话框后,DataGridView的选定行重置

时间:2014-11-27 13:19:37

标签: c# winforms datagridview

我有一个基于System.Windows.Forms.Form的对话框。它包含一个控件DataGridView。 我填写此DataGridView,然后选择任何行。稍后调用我的表单ShowDialog的方法。在显示表单后,我可以看到所选的第一行DataGridView,但未选中我想要的行。我该如何解决这个问题?我希望方法OnLoad

中没有选择make

以下是我的代码。

DgvDataSource dgvDs = new DgvDataSource(); 
DgvForm dgvF = new DgvForm();

dgvF.DataSource = dgvDs; 
dgvF.SelectRows(new int[] { 3, 5, 7, 9, 10}); dgvF.ShowDialog();

 public class DgvForm : Form 
 {
    public DgvForm()
    {
        InitializeComponent();
    }

    DgvDataSource dataSource;
    public DgvDataSource DataSource
    {
        get { return myDataGridView.DataSource; }
        set
        {
            myDataGridView.DataSource = value;
        }
    }

    public void SelectRows(int[] indexes)
    {
        myDataGridView.ClearSelection();
        foreach (DataGridViewRow r in dataGridView1.Rows)
        {
            r.Cells[0].Selected = indexes.Contains(r.Index);
        }

    } 
}

public class DgvDataSource
{
    public BindingList<DgvItem> Items { get; private set; }

    public DgvDataSource()
    {
        InitItems();
    }

    void InitItems()
    {
        Items = new BindingList<DgvItem>();
        for (int i = 0; i < 20; i++)
        {
            Items.Add(new DgvItem() { Id = i + 1, 
                                        Description = "Description " + (i+1).ToString() });
        }
    }
}

public class DgvItem
{
    public int Id { get; set; }
    public string Description { get; set; }
}

1 个答案:

答案 0 :(得分:0)

将SelectRows放入对话框表单中的加载事件中。创建实例时,设置int []属性:

 DgvForm dgvF = new DgvForm();
 //this property should be in the Dialog Form 
 dgvF.Selection = new int[] { 3, 5, 7, 9, 10}; 
 dgvF.ShowDialog();


Luego en el Form:

private int[] selection;

public int[] Selection
{
get { return selection; }
set { selection = value; }
}
private void Form1_Load(object sender, EventArgs e)
{
//Put your code here, to load DataSource and Select Rows.
}