コンボボックスの選択値を変えるごとにDataGridViewで表示するデータを変更するにはDataViewを使用するのが便利かと思います。 DataTableなどにも一致する行を取得するメソッドがありますが、こちらのほうが便利かと思います。
C#
public partial class Form2 : Form { DataTable dt = new DataTable(); DataTable dt2 = new DataTable(); public Form2() { InitializeComponent(); } private void Form2_Load(object sender, EventArgs e) { SqlConnectionStringBuilder connBldr = new SqlConnectionStringBuilder(); connBldr.DataSource = @".\SQLExpress"; connBldr.InitialCatalog = "pubs"; connBldr.IntegratedSecurity = true; SqlConnection conn = new SqlConnection(connBldr.ConnectionString); SqlCommand cmd = new SqlCommand(); cmd.Connection = conn; cmd.CommandText = "SELECT minit FROM employee GROUP BY minit ORDER BY minit"; SqlDataAdapter sda = new SqlDataAdapter(); sda.SelectCommand = cmd; //コンボボックス用のデータを取得 sda.Fill(dt); //DataGridViewのデータを取得 cmd.CommandText = "SELECT * FROM employee"; sda.Fill(dt2); //次を設定しないと表示がおかしくなります。 comboBox1.DisplayMember = "minit"; comboBox1.ValueMember = "minit"; comboBox1.DataSource = dt; dataGridView1.DataSource = dt2; } private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) { DataView dv = dt2.DefaultView; //ここでフィルターを設定します。 dv.RowFilter = "minit = '" + this.comboBox1.SelectedValue.ToString() + "'"; } }
VB.NET
Imports System.Data.SqlClient Imports System.Data Public Class Form1 Dim dt As DataTable = New DataTable() Dim dt2 As DataTable = New DataTable() Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim connBldr As SqlConnectionStringBuilder = New SqlConnectionStringBuilder() connBldr.DataSource = "." connBldr.InitialCatalog = "pubs" connBldr.IntegratedSecurity = True Dim conn As SqlConnection = New SqlConnection(connBldr.ConnectionString) Dim cmd As SqlCommand = New SqlCommand() cmd.Connection = conn cmd.CommandText = "SELECT minit FROM employee GROUP BY minit ORDER BY minit" Dim sda As SqlDataAdapter = New SqlDataAdapter() sda.SelectCommand = cmd 'コンボボックス用のデータを取得 sda.Fill(dt) 'DataGridViewのデータを取得 cmd.CommandText = "SELECT * FROM employee" sda.Fill(dt2) '次を設定しないと表示がおかしくなります。 Me.ComboBox1.DisplayMember = "minit" Me.ComboBox1.ValueMember = "minit" Me.ComboBox1.DataSource = dt Me.DataGridView1.DataSource = dt End Sub Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged Dim dv As DataView = dt2.DefaultView 'ここでフィルターを設定します。 dv.RowFilter = "minit = '" & Me.ComboBox1.SelectedValue.ToString() & "'" End Sub End Class