为SmartGrid控件设置与绑定数据源(DataSource)
SmartGrid的DataSource属性用来存取或设置数据源,数据源的类型可以为XML文档、DataTable、DataSet、SqlDataReader、OdbcDataReader、OleDataReader等。实现了System.ComponentModel.IListSource或System.Collections.IEnumerable接口或继承自System.Xml.XmlElement的对象都可作为其数据源。
注意:
如果DataSource类型为DataSet,且同时指定了DataMember属性(数据表名),则使用DataSet中指定的数据表填充数据,否则取第一个数据表(Tables[0])填充数据。
下面我们就为SmartGrid绑定DataTable,XML,DataReader,DataSet各举一个实例,其它类型数据源,大家自己举一反三了。
(1)为SmartGrid绑定DataTable示例:string _connectionstring="Data Source=192.168.1.1;Initial Catalog=test;UID=sa;Password=xxxxxx";
DataSet currentDs = new DataSet();
using (SqlConnection currentConn = new SqlConnection(_connectionstring))
{
//获取数据
currentConn.Open();
SqlDataAdapter currentSda = new SqlDataAdapter("select * from table1", currentConn);
currentSda.Fill(currentDs, "table1");
this.SmartGrid1.DataSource = currentDs.Tables["table1"];
this.SmartGrid1.DataBind();
}
(2)为SmartGrid绑定XML示例:protected void btnLoadData_XML_Click(object sender, EventArgs e)
{
DataSet currentDs = new DataSet();
using (SqlConnection currentConn = new SqlConnection(_connectionstring))
{
//获取数据
currentConn.Open();
SqlDataAdapter currentSda = new SqlDataAdapter("select * from table1", currentConn);
currentSda.Fill(currentDs, "table1");
XmlDocument xmlDocument = MyConvertDataTableToXML(currentDs.Tables["table1"]);
this.SmartGrid1.DataSource = xmlDocument.DocumentElement;
this.SmartGrid1.DataBind();
}
}
(3)为SmartGrid绑定DataReader示例:protected void btnLoadData_SqlDataReader_Click(object sender, EventArgs e)
{
string selectCmd = "select * from table1";
DataSet currentDs = new DataSet();
using (SqlConnection currentConn = new SqlConnection(_connectionstring))
{
//获取数据
currentConn.Open();
SqlCommand currentCmd = new SqlCommand();
currentCmd.CommandType = CommandType.Text;
currentCmd.CommandText = selectCmd;
currentCmd.Connection = currentConn;
SqlDataReader currentSdr = currentCmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(currentSdr);
currentSdr.Close();
this.SmartGrid1.DataSource = dt;
this.SmartGrid1.DataBind();
}
}
(4)为SmartGrid绑定DataSet示例:protected void btnLoadData_DataSet_Click(object sender, EventArgs e)
{
DataSet currentDs = new DataSet();
using (SqlConnection currentConn = new SqlConnection(_connectionstring))
{
//获取数据
currentConn.Open();
SqlDataAdapter currentSda = new SqlDataAdapter("select * from table1", currentConn);
currentSda.Fill(currentDs, "table1");
this.SmartGrid1.DataSource = currentDs;
this.SmartGrid1.DataBind();
}
}
以上是为SmartGrid绑定四种不同数据源的示例,供大家参考。w