using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
public partial class Sample_DataSoure : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
SetDataBind();
}
}
void SetDataBind()
{
string conStr = "Data Source = (local);Integrated Security = SSPI;Initial Catalog = pubs;";
SqlConnection con = new SqlConnection(conStr);
//GridView1
string comStr = "Select * From jobs";
SqlDataAdapter da = new SqlDataAdapter(comStr, con);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds;//适用于DataSet中只有一个表
GridView1.DataBind();
//GridView2
string comStr2 = "Select * From jobs Select * From sales";
SqlDataAdapter da2 = new SqlDataAdapter(comStr2, con);
DataSet ds2 = new DataSet();
//da2.TableMappings.Add("Table", "ds_jobs");
//da2.TableMappings.Add("Table1", "ds_sales");
da2.Fill(ds2);
GridView2.DataSource = ds2.Tables[0];//适用于DataSet中有多个表
//GridView2.DataSource = ds2.Tables["ds_jobs"];
GridView2.DataBind();
/*
* 当使用了da2.TableMappings.Add("Table", "ds_jobs");和da2.TableMappings.Add("Table1", "ds_sales");这两句后,
* 就可以使用GridView2.DataSource = ds2.Tables["ds_jobs"];替换GridView2.DataSource = ds2.Tables[0];了。
* 解释:
* 默认的情况下Fill(ds,"TableName") or Fill(ds);后ds中的第一个表名(TableName)是被默认映射为Table,第二个被默认映射为Table1,
* 第三个被默认映射为Table2,以此类推……
* 如果用了TableMappings,那么这些Table,Table1,Table2就可以用TableMappings中指定的名称,
* 这样就可以通过ds.Table[TableName]来访问一个具体名称的表了.
* 所以上面的代码中如果没有使用TableMappings也可以通过ds2.Tables["Table"];来返回数据库中的jobs表,
* 使用ds2.Tables["Table1"];来返回数据库中的sales表。
*/
//GridView3
ds.Tables[0].DefaultView.RowFilter = "job_id > 10";
GridView3.DataSource = ds.Tables[0].DefaultView;//适用于需要筛选后的数据
//如上面代码筛选了job_id > 15 的数据
GridView3.DataBind();
}
}