ADO.NET 中DataTable中加载数据方法

来源:互联网 发布:海关数据编码 编辑:程序博客网 时间:2024/05/01 11:32
ADO.NET 中DataTable中加载数据又两种方法

第一种 
 
//使用fill方法填充DataTable 

private void useDataTableByFill() 
    

        SqlConnection myConnection 
= new SqlConnection(ConfigurationManager.ConnectionStrings["sqlConnectionString"].ConnectionString); 
        DataTable myDataTable 
= new DataTable(); 

        SqlDataAdapter myDp 
= new SqlDataAdapter("select * from authors", myConnection); 
        myDp.Fill(myDataTable); 

        GridView1.DataSource 
= myDataTable.DefaultView; 
        GridView1.DataBind(); 
        
        myConnection.Dispose(); 
        myDp.Dispose();        

    }
 

第二种 
//使用DataReader方法 
    private void useDataTableByDataReader() 
    

        SqlConnection myConnection 
= new SqlConnection(ConfigurationManager.ConnectionStrings["sqlConnectionString"].ConnectionString); 
        DataTable myDataTable 
= new DataTable(); 

        SqlCommand myCommand 
= new SqlCommand("select * from authors", myConnection); 
        myConnection.Open(); 

        SqlDataReader dr 
= myCommand.ExecuteReader(CommandBehavior.CloseConnection); 
        myDataTable.Load(dr); 

        GridView1.DataSource 
= myDataTable.DefaultView; 
        GridView1.DataBind(); 

        dr.Close(); 
        dr.Dispose(); 
        myCommand.Dispose();                
    }
 

 
原创粉丝点击