How to Search in a DataView

The DataView provides different views of the data stored in a DataTable. The constructor for the DataView class initializes a new instance of the DataView class and accepts the DataTable as an argument. We can create DataView in two ways. Either we can use the DataView Constructor , or we can create a reference to the DefaultView property of the DataTable. We can create multiple DataViews for any given DataTable.A DataView provides a dynamic view of data in the underlying DataTable: the content,ordering, and membership reflect changes as they occur.

We can search in a DataView according to the sort key values by using the Find method . The Find method returns an integer with the index of the DataRowView that matches the search criteria. If more than one row matches the search criteria, only the index of the first matching DataRowView is returned. If no matches are found, Find returns -1.

using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;

namespace WindowsApplication1
    public partial class Form1 : Form
        public Form1()

        private void button1_Click(object sender, EventArgs e)
            string connetionString = null;
            SqlConnection connection ;
            SqlCommand command ;
            SqlDataAdapter adapter = new SqlDataAdapter();
            DataSet ds = new DataSet();
            DataView dv ;
            string sql = null;
            connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password";
            sql = "Select * from product";
            connection = new SqlConnection(connetionString);
                command = new SqlCommand(sql, connection);
                adapter.SelectCommand = command;
                adapter.Fill(ds, "Find Row DataView");

                dv = new DataView(ds.Tables[0]);
                dv.Sort = "Product_Name";
                int index = dv.Find("PRODUCT5");
                if (index == -1)
                    MessageBox.Show ("Item Not Found");
                    MessageBox.Show(dv[index]["Product_id"].ToString() + " " + dv[index]["Product_Name"].ToString());

            catch (Exception ex)
} (C) 2021    Founded by raps mk
All Rights Reserved. All other trademarks are property of their respective owners.
SiteMap  | Terms  | About