c# 查找表中行


查询行,是使用Table.Rows.find()方法。

主要方法为:

     将主查找的Column设为主键。

     使用Find()方法进行查找。

    

 

using  System.Data.SqlClient;

namespace  FindingData
{
    
public   partial   class  Form1 : Form
    {
        
public  Form1()
        {
            InitializeComponent();
            btnFind.Click 
+=   new  EventHandler(btnFind_Click);

            UpdateData();
        }

        
void  btnFind_Click( object  sender, EventArgs e)
        {
            FindData();
        }


        
string  sConnection  =   " Data Source=scott;Initial Catalog=northwind;Persist Security Info=True;User ID=sa;Password=sa123 " ;
        DataSet dsSet 
=   new  DataSet();
        SqlDataAdapter sdaAdapter 
=   null ;
        SqlCommandBuilder scbBuilder 
=   null ;
        
private   void  UpdateData()
        {
            
// 建立Connection
            SqlConnection scConnection  =   new  SqlConnection(sConnection);
            
// 建立Command
            SqlCommand scCommand  =  scConnection.CreateCommand();
            scCommand.CommandText 
=   " select customerID,companyName from customers " ;
            
// 建立Adapter
            sdaAdapter  =   new  SqlDataAdapter(scCommand);

            
// 该对象负责生成用于更新数据库的SQL语句,不必自己创建这些语句
            scbBuilder  =   new  SqlCommandBuilder(sdaAdapter);

            
// 得到数据
            sdaAdapter.Fill(dsSet,  " customers " );
            dgvView.DataSource 
=  dsSet.Tables[ " customers " ];
        }

        
private   void  FindData()
        {
            DataColumn[] dcKeys 
=   new  DataColumn[ 1 ];
            dcKeys[
0 =  dsSet.Tables[ " customers " ].Columns[ " customerID " ];
            
// 设置表的主键
            dsSet.Tables[ " customers " ].PrimaryKey  =  dcKeys;
            
// 查找主键包含的行
            DataRow drFindRow  =  dsSet.Tables[ " customers " ].Rows.Find( " ZaCzi " );

            
if  (drFindRow  !=   null )
            {
                
// 复制表架构
                DataTable dtNew  =  dsSet.Tables[ " customers " ].Clone();
                
// 建立表中的行
                DataRow drRow  =  dtNew.NewRow();
                drRow[
0 =  drFindRow[ 0 ];
                drRow[
1 =  drFindRow[ 1 ];
                
// 将行资料增加到新表中
                dtNew.Rows.Add(drRow);
                
//在DataGrieView中 显示查出的行
                dgvView.DataSource  =  dtNew;
            }

        }

    }
}

 

 

你可能感兴趣的:(C#)