重发:
为什么:把Dataset绑定到Datagrid,一般来说,需要把一个Dataview绑定到Datagrid,而不是直接绑定Dataset. 如:
DataSet dsSel = new DataSet();
conn = new OleDbConnection(sConn);
OleDbDataAdapter MyAdapter = new OleDbDataAdapter(strSel,conn);
MyAdapter.Fill(dsSel,"CQBianRenBG");
DataGrid1.DataSource = dsSel.Tables["CQBianRenBG"].DefaultView;//为什么一般不直接等于dsSel?
DataGrid1.DataBind();
为什么:把Dataset绑定到Datagrid,一般来说,需要把一个Dataview绑定到Datagrid,而不是直接绑定Dataset. 如:
DataSet dsSel = new DataSet();
conn = new OleDbConnection(sConn);
OleDbDataAdapter MyAdapter = new OleDbDataAdapter(strSel,conn);
MyAdapter.Fill(dsSel,"CQBianRenBG");
DataGrid1.DataSource = dsSel.Tables["CQBianRenBG"].DefaultView;//为什么一般不直接等于dsSel?
DataGrid1.DataBind();
数据源一般使用DataTable或DataView。
DataTable.DefaultView是一个DataTable的默认视图,它是一个DataView。
实际上
DataGrid1.DataSource = dsSel.Tables["CQBianRenBG"].DefaultView;
与
DataGrid1.DataSource = dsSel.Tables["CQBianRenBG"];
在你的代码里是等效的。
DataSet好象是不能直接做为数据源的。
方法是 this.dataGrid1.DataSource = MyDataSet.Tables["表名"];
或着:
this.dataGrid1.DataSource = MyDataSet.Tables["表名"].DefaultView;
其实把DataSet理解为在内存中的数据库就行了;
SqlConnection cn;
SqlDataAdapter da;
SqlDataAdapter d;
DataSet ds;
String strSQL;
String strS;
cn=new SqlConnection("server=BSERVER;uid=sa;pwd=;database=pubs");
try
{
cn.Open();
Response.Write("服务器已经联接!"+"<BR>");
Response.Write(cn.Database+" "+"服务器状态是:");
Response.Write(cn.State+"<BR>");
Response.Write("<BR>");
strSQL="Select au_fname,au_lname from authors";
strS="Select au_fname from authors";
da=new SqlDataAdapter(strSQL,cn);
d=new SqlDataAdapter(strS,cn);
ds=new DataSet();
da.Fill(ds,"Authors");
d.Fill(ds,"A");
DataGrid1.DataSource=ds.Tables["Authors"].DefaultView;
DataGrid1.DataBind();
DataGrid2.DataSource=ds.Tables["A"].DefaultView;
DataGrid2.DataBind();
}
catch(SqlException sx)
{
Response.Write("Connection failed:"+sx.Message);
}
finally
{
if(cn.State==ConnectionState.Open)
cn.Close();
}
我真服了你!
MyDataSet.Tables["表名"]
难道你还没有理解这是个什么对象么?
这是个DataTable对象。如果有什么怀疑请查看MyDataSet.Tables["表名"].GetType()
也就是说你实际绑定的是个DataTable对象。this.dataGrid1.DataSource = MyDataSet.Tables["表名"];
上句是你自己的代码,它就是把dataGrid1绑定到DataSet中的表名为“表名”的DataTable。
那个Tables就是一个TableCollection(DataTable的集合)。
你所做的不是将控件绑定到DataSet,而是绑定到DataSet中的一张DataTable。这就是你那段代码的意思。