在两个不同的Form窗体中的DataGridView数据“传递”

在写程序时,遇到要在一个Form窗体中的DataGridView中选择数据,然后添加到另外一个Form窗体中的DataGridView中。因为我想只点中某行的某个Cell就可以把这整行的内容取出来(即在某一行数据中,我随便点中一个Cell,就算选中了这整行数据)。举个例子如下:

首先我在左边选择一些Cell,然后添加就可以添加到右边那里:

在两个不同的Form窗体中的DataGridView数据“传递”_第1张图片

效果如下:

在两个不同的Form窗体中的DataGridView数据“传递”_第2张图片


下面是实现的代码:

1、首先在主窗体调用子窗体的时候写这个(这里我是用一个按钮来触发):

private void addDatabaseButton_Click(object sender, EventArgs e)
{
     FactDatabaseForm factDB_Form = new FactDatabaseForm();
     factDB_Form.Owner = this;
     factDB_Form.Show(); // 或者factDB_Form.ShowDialog();
}
2、在子窗体里面:
private void Form2_Load(object sender, EventArgs e)
{
     mainForm = (MainForm)this.Owner;  // 获得主窗体的引用
     mainCurDGV = mainForm.curDGV;     // 获得主窗体中的那个DataGridView

     // TODO: This line of code loads data into the 'myDataSet.FactDB' table. You can move, or remove it, as needed.
     this.factDBTableAdapter.Fill(this.myDataSet.FactDB);
}
3、然后在按钮“把所选行增加到当前要推导的事实库中”的事件处理函数里面:
private void saveToCurFactDB_Click(object sender, EventArgs e)
        {
            Dictionary dicts = new Dictionary();

            // 得到选中的行(不管是以整行选中,还是只是选中某行的某个单元,认为选中了该行),并且把这行的东西放到Dictionary里面
            int key;
            foreach (DataGridViewCell cell in this.factDatebaseDataGridView.SelectedCells)
            {
                key = Convert.ToInt32(factDatebaseDataGridView.Rows[cell.RowIndex].Cells[0].Value); // 得到该行中的那个"factID"
                if (!mainForm.mainDict.ContainsKey(key))  // 避免有重复
                {
                    mainForm.mainDict.Add(key, factDatebaseDataGridView.Rows[cell.RowIndex].Cells[1].Value);
                    dicts.Add(key, factDatebaseDataGridView.Rows[cell.RowIndex].Cells[1].Value);
                }
            }

            if(dicts.Count > 0)   // 如果选择了一些在当前事实库没有的基才执行下面的
            {
                DataGridViewRow[] rows = new DataGridViewRow[dicts.Count];
                foreach (var dict in dicts)
                {
                    addItems(dict.Key, dict.Value as string);
                }

                mainCurDGV.Sort(mainCurDGV.Columns[0], ListSortDirection.Ascending);
                MessageBox.Show("增加成功!", "消息");
            }
            else
            {
                MessageBox.Show("当前事实库已经存在你选择的这些事实", "提示");
            }
        }

        private void addItems(int iFactID, string strFactName)
        {
            //此处的代码不能进行循环!必须封装为一个方法,通过方法的循环,才能实现循环!
            DataGridViewRow dgvr = new DataGridViewRow();
            foreach (DataGridViewColumn c in this.factDatebaseDataGridView.Columns)
            {
                dgvr.Cells.Add(c.CellTemplate.Clone() as DataGridViewCell);
            }
            dgvr.Cells[0].Value = iFactID;
            dgvr.Cells[1].Value = strFactName;
            mainCurDGV.Rows.Add(dgvr);
        }
这里对上面代码再简单说明一下 ,如果要取得DataGridView中的某一行,可以这样写:
dataGridView.Rows[i];
得到某一行的某个单元:
dataGridView.Rows[i].Cells[j]



你可能感兴趣的:(.Net学习笔记)