grid1中的选定项目显示了grid2中tabele2的相关项目

时间:2013-04-11 14:37:09

标签: c# datagridview ado.net

我正在努力实现以下目标:

我的第一个网格显示了我的数据库table foo中的条目,当选择一个时,我需要从列[0]单元格[0]中恢复,这是我之后用于查询的ID 。此查询将使用table bar中的所有一对多实例填充grid2。但我得到一个零点异常,我无法弄清楚为什么......

private void button1_Click_1(object sender, EventArgs e)
        {
            SqlConnection sc = new SqlConnection(@"Data Source = WARZARU-NB\SQLEXPRESS; Database = proj_1; Integrated Security = True");

            dataSet.Clear();

            dataAdapter.SelectCommand = new SqlCommand("select * from students WHERE id=@index", sc);
      // EXCEPTION here
            dataAdapter.InsertCommand.Parameters.Add("@index", SqlDbType.Int).Value = dgParent.CurrentCell.Value; 
            dataAdapter.Fill(dataSet, "grades");

            dgChild.DataSource = dataSet.Tables["grades"];

            dgParent.AutoResizeColumns();
            dgParent.AutoResizeRows();
        }

1 个答案:

答案 0 :(得分:0)

仍然不是正确的方法,但它有效...

  private void dgParent_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            SqlConnection sc = new SqlConnection(@"Data Source = WARZARU-NB\SQLEXPRESS; Database = proj_1; Integrated Security = True");
        if (dgParent.SelectedCells.Count > 0)
        {
            dgChild.DataSource = null;
            int selectedrowindex = dgParent.SelectedCells[0].RowIndex;
            DataGridViewRow selectedRow = dgParent.Rows[selectedrowindex];
            string a = Convert.ToString(selectedRow.Cells["id"].Value);
            MessageBox.Show(a);

            SqlCommand updateCommand1 = new SqlCommand("Select * FROM tableChild WHERE studentID = @id", sc);
            updateCommand1.Parameters.Add(new SqlParameter("id", a));
            dataAdapter = new SqlDataAdapter(updateCommand1);

            dataSetChild.Clear();
            dataAdapter.Fill(dataSetChild, tableChild);
            dgChild.DataSource = dataSetChild.Tables[tableChild];
        }

        dgParent.AutoResizeColumns();
        dgParent.AutoResizeRows();
    }