zoukankan      html  css  js  c++  java
  • 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;
                }

            }

        }
    }
  • 相关阅读:
    Entity Framework 教程
    C# yield
    表达式树系列文章汇总
    C#中静态与非静态方法比较
    谈谈对Spring IOC的理解
    工厂方法模式与IoC/DI
    通过配置的方式Autofac 《第三篇》
    Autofac 组件、服务、自动装配 《第二篇》
    Autofac 解释第一个例子 《第一篇》
    SQL Server索引调优系列
  • 原文地址:https://www.cnblogs.com/scottckt/p/1268684.html
Copyright © 2011-2022 走看看