日期:2014-05-18  浏览次数:20502 次

如何绑定DataGrid
如何绑定DataGrid

------解决方案--------------------
 
 protected void Page_Load(object sender, EventArgs e)
{

if (!this.Page.IsPostBack)
{

DataGrid1.DataSource = CreateDataSource();
DataGrid1.DataBind();
}
}
public DataView CreateDataSource()
{

DataTable dt = new DataTable();
DataRow dr;
dt.Columns.Add(new DataColumn("身份证号码", typeof(string)));
dt.Columns.Add(new DataColumn("图书单价", typeof(decimal)));
dt.Columns.Add(new DataColumn("购买数量", typeof(Int32)));
dt.Columns.Add(new DataColumn("总价格", typeof(decimal)));


for (int i = 0; i < 30; i++)
{
dr = dt.NewRow();

dr[0] = "123456789123456789";
dr[1] = 100 * i / 3.0;
dr[2] = i + 5;
dr[3] = (decimal)dr[1] * (Int32)dr[2];
dt.Rows.Add(dr);
}
DataView dv = new DataView(dt);
return dv;
}

------解决方案--------------------
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string myConstr = WebConfigurationManager.AppSettings["testConnectionString"].ToString();
string mySql = "select top 500 * from lucky749";
SqlConnection myConn = new SqlConnection(myConstr);
SqlDataAdapter myAdapter = new SqlDataAdapter(mySql, myConn);
DataSet myDataset=new DataSet();
myAdapter.Fill(myDataset);
try
{
myConn.Open();
DataGrid1.DataSource = myDataset.Tables[0].DefaultView;
DataGrid1.DataBind();
}
catch
{
}
finally

myConn.Close();
}
}

}