如何根据主窗体上的条件更新另一个窗体gridviewdata?

时间:2015-10-01 11:58:55

标签: c# winforms gridview datagridview

我有两种表单MainForm.csPopupForm.cs

MainForm.cs按钮上单击我将打开另一个表单,并希望逐个显示一个值,以便循环进入网格视图行

foreach (var item in listBox1.Items)
{
    //which executes cmd commands for ItemListBox and based on that Want to show current item on grid view which is on PopupForm.cs
    // show gridview item
    // grid view bind
    PopupForm obj = new PopupForm(listBox1.Items);
    obj.ShowDialog();
}

PopupForm.cs

ListBox.ObjectCollection _projectList;
public PopupForm(ListBox.ObjectCollection objectCollection)
{
    _nameList = objectCollection;
    InitializeComponent();
}

private void PopupForm_Load(object sender, EventArgs e)
{
    DataTable dt = new DataTable();
    dt.Columns.Add("Name");

    foreach (string items in _nameList )
    {
        DataRow row = dt.NewRow();
        dt.Rows.Add(items);
    }

    this.myGridView.DataSource = dt;
}

但这会一举绑定所有物品。如何循环显示逐个项目?

1 个答案:

答案 0 :(得分:1)

由于您希望在循环中逐个显示项目,您可能需要将整个集合传递到对话框表单,然后使用计时器显示每个项目:

playbackLikelyToKeepUp

您不必在循环中显示表单,因此只需传递集合并显示表单:

ListBox.ObjectCollection nameList;
DataTable dt = new DataTable();
private int rowIndex = 0;
private Timer timer = new Timer();

public PopupForm(ListBox.ObjectCollection objectCollection) {
  this.InitializeComponent();
  dt.Columns.Add("List");
  myGridView.DataSource = dt;
  nameList = objectCollection;
  timer.Interval = 1000;
  timer.Tick += timer_Tick;
  timer.Start();
}

private void timer_Tick(object sender, EventArgs e) {
  if (rowIndex >= nameList.Count) {
    timer.Stop();
  } else {
    DataRow row = dt.NewRow();
    row[0] = nameList[rowIndex];
    dt.Rows.Add(row);
    rowIndex++;
  }
}