How to filter data in a Dataset in vb.net

Following example shows how to use data after filtering in dataset

Example has one One ComboBox control named ComboBox1 and one Datagridview control named DatagridView1 and one Button with name button1. And we a table that has following data:

Table name (SQL table): tbl_Employee

Employee IdEmpNameAgeDepartment
1Ankur28Sales
2David32Sales
3John30HR
4James45Production
5Mohan35Production
6Ram40HR

 

Now we want to show all information of the employee according to selected employee of ComboBox control, there are two common ways for doing this. First we retrieve the data by Query each time according to selected employee and second is we retrieve data from table into DataSet object at one time and show the information after filtering data from dataset according to selected employee.

following code shows how to filtering data from dataset according to selected employee:

Retrieve all data from tbl_employee into DataSet

    Private Sub MakeDataset()
        Dim ConnectionString = "Data Source=SqlServer Instance Name; Initial Catalog=EmployeeDatabase;Integrated Security=true"
        Dim SqlCon As New SqlClient.SqlConnection
        SqlCon.ConnectionString = ConnectionString
        SqlCon.Open()
        Dim cmd As New SqlClient.SqlCommand
        cmd.Connection = SqlCon
        cmd.CommandText = "Select * from tbl_employee"
        cmd.CommandTimeout = 6000
        Dim oDataAdapter As New SqlClient.SqlDataAdapter(cmd)
        oDataAdapter.Fill(ds)
    End Sub

Bind Combobox with all employee names

Private Sub BindComboBox()
   For i As Integer = 0 To ds.Tables(0).Rows.Count - 1
      ComboBox1.Items.Add(ds.Tables(0).Rows(i)("EmpName"))
   Next
End Sub

Show data in DataGridView according to selected employee

Private Sub Button1_Click(ByVal sender As System.Object, _
            ByVal e As System.EventArgs) Handles Button1.Click
  ds.Tables(0).DefaultView.RowFilter = "EmpName= '" & ComboBox1.Text & "'"
  DataGridView1.DataSource = ds.Tables(0).DefaultView
End Sub
 
<img class="aligncenter size-full wp-image-1165" title="Filteringdataset" src="http://img.authorcode.com/ac/2011/07/Filteringdataset.jpg" alt="" width="464" height="240" />