日期:2012-05-08  浏览次数:20477 次

在后代码里创建DataGrid控件
本文介绍如何用代码创建DataGrid,并且有四个绑定列和一个模板列,支持排序功能。

代码如下:

C#

CreateDataGrid.aspx

<%@ Page language="c#" EnableViewState = "false"Codebehind="CreateDataGrid.aspx.cs"
AutoEventWireup="true" Inherits="aspxWebCS.myDataGrid" %>
<script runat="server">
public void Page_Load(Object sender,EventArgs e){
CreateDataGridForm.Controls.Add(MakeGrid());
}
</script>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
<title>用代码创建DataGrid</title>
<meta name="GENERATOR" Content="Microsoft Visual Studio 7.0">
<meta name="CODE_LANGUAGE" Content="C#">
<meta name="vs_defaultClientScript" content="JavaScript">
<meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
</HEAD>
<body MS_POSITIONING="GridLayout">
<form id="CreateDataGridForm" method="post" runat="server">
<div align="center"><b>用代码创建DataGrid</b></div>
</form>
</body>
</HTML>

CreateDataGrid.aspx.cs

using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Drawing;

/// <summary>
/// CreateDataGrid 的摘要说明。
/// </summary>
namespace aspxWebCS
{
public class myDataGrid : Page
{
public String sql = "Select FirstName,LastName,HomePhone,Title FROM Employees";
public DataGrid mygrid = new DataGrid();
public String SortExpression;

/// <summary>
/// 创建一个模板列和一个列模板
/// </summary>

public TemplateColumn tm = new TemplateColumn();
public ColumnTemplate mycol = new ColumnTemplate();

//返回DataView
public DataView CreateDataSource ()
{
string strSql;
strSql = "Data Source=.;Initial Catalog=Northwind;User Id=sa;Password=;";
SqlConnection conn = new SqlConnection(strSql);
SqlDataAdapter db_sqladaptor = new SqlDataAdapter(sql,conn);
DataSet ds = new DataSet();
db_sqladaptor.Fill(ds,"Employees");
DataView myView = ds.Tables["Employees"].DefaultView;
//myView.Sort=SortExpression;
//Response.Write(sql);
return myView;
}

/// <summary>
/// 处理排序
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void Sort_Grid(Object sender, DataGridSortCommandEventArgs e)
{
SortExpression = e.SortExpression.ToString();
Session["SortField"]=SortExpression.Trim();
if(Session["Order"]==null) Session["Order"] = "ASC";
Session["Order"] = (Session["Order"].ToString()=="DESC")?"ASC":"DESC";
if(Session["SortField"]==null) Session["SortField"] = "FirstName";
sql += " ORDER BY "+Session["SortField"].ToString() + " " + Session["Order"].ToString();
mygrid.DataSource = CreateDataSource();
mygrid.DataBind();
}
/// <summary>
/// 创建和设置DataGrid属性,这里的属性设置为固定值,但也可以动态设置
/// </summary>
/// <returns></returns>

public DataGrid MakeGrid()
{
mygrid.CellPadding=2;