grid1中的Selected item显示grid2中table2中的相关项

本文关键字:table2 grid2 中的 Selected item 显示 grid1 | 更新日期: 2023-09-27 18:08:34

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

我有我的第一个网格,它显示了我的db table foo的条目,当选择一个时,我需要从列[0]单元格[0]恢复,一个id,我将用于查询之后。该查询将用table bar中的所有单多实例填充grid2。但是我得到一个null点异常,我不知道为什么…

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();
        }

grid1中的Selected item显示grid2中table2中的相关项

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

  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();
    }