我有2个dataGridViews . 左边的一个数据来自一个名为Fitness_Manager的表,一个数据首先没有任何内容,如图所示:
我想点击一个随机行,然后从右边的dataGridView中显示他的孩子(2个表格是1:n关系) . 但是当我在dataGridView2中选择第一行(例如)时,会显示其子项,但也会显示dataGridView1中的列名:
the columns from the 2 dataGrids are the same
此外,dataGridView1删除我不想要的所有数据:
the children are shown but dataGridView1 is changed
我怎样才能解决这个问题?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Sql
{
public partial class Form1 : Form
{
SqlConnection connection = new SqlConnection("Data source=DESKTOP-EDEJRBT; Initial Catalog=FitnessManager; Integrated Security=True");
SqlDataAdapter adapter = new SqlDataAdapter();
DataSet set = new DataSet();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
adapter.SelectCommand = new SqlCommand("Select * from Fitness_Manager",connection);
set.Clear();
adapter.Fill(set);
dataGridView1.DataSource = set.Tables[0];
}
private void button2_Click(object sender, EventArgs e)
{
try
{
adapter.InsertCommand = new SqlCommand("Insert Into Sali(oras,capacitate,codFM) VALUES(@b,@c,@d)", connection);
adapter.InsertCommand.Parameters.Add("@b", SqlDbType.NVarChar).Value = textBox2.Text;
adapter.InsertCommand.Parameters.Add("@c", SqlDbType.Int).Value = Int32.Parse(textBox3.Text);
string idS = dataGridView1.SelectedRows[0].Cells[0].Value + string.Empty;
adapter.InsertCommand.Parameters.Add("@d", SqlDbType.Int).Value = Int32.Parse(idS);
connection.Open();
adapter.InsertCommand.ExecuteNonQuery();
connection.Close();
}catch(Exception ex)
{
MessageBox.Show(ex.Message);
connection.Close();
}
}
private void dataGridView2_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex >= 0)
{
// string idS = dataGridView1.SelectedRows[0].Cells[0].Value + string.Empty;
//int id = Int32.Parse(idS);
DataGridViewRow row = this.dataGridView1.Rows[e.RowIndex];
string idS = row.Cells["codf"].Value.ToString();
int id = Int32.Parse(idS);
adapter.SelectCommand = new SqlCommand("Select cods,oras,capacitate from Sali Where codFM=" + id, connection);
set.Clear();
adapter.Fill(set);
dataGridView2.DataSource = set.Tables[0];
}
}
private void label2_Click(object sender, EventArgs e)
{
}
}
}