本例用代码实现了创建DataGrid并响应了CheckBox事件,并实现了超链接列的多变量传送。
创建一个前台页面
CreateDataGrid.aspx:
在Form中添加一个PlcaeHolder,ID为"ph",Runat="Server"
后台页面
CreateDatagrid.aspx.cs
public class CreateDataGrid : System.Web.UI.Page
{
public String sql = "Select FirstName,LastName,HomePhone,Title FROM Employees";
public DataGrid mygrid = new DataGrid();
protected System.Web.UI.WebControls.PlaceHolder ph;
public String SortExpression;
private void Page_Load(object sender, System.EventArgs e)
{
//CreateDataGridForm.Controls.Add(MakeGrid());
this.ph.Controls.Add(MakeGrid());
}
// protected override void CreateChildControls()
// {
//base.CreateChildControls ();
//}
#region Web 窗体设计器生成的代码
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
//
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
/// <summary>
/// 创建一个模板列和一个列模板
/// </summary>
public TemplateColumn tm = new TemplateColumn();
public ColumnTemplate mycol = new ColumnTemplate();
//返回DataView
public DataView CreateDataSource ()
{
string strSql;
strSql = "Data Source=localhost;Initial Catalog=Northwind;User Id=sa;Password=sa;";
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;
mygrid.Attributes.Add("align","center");
mygrid.CellSpacing=0;
mygrid.Width=500;
mygrid.BorderWidth=1;
mygrid.BorderColor=ColorTranslator.FromHtml("Black");
mygrid.AutoGenerateColumns=false;
mygrid.ForeColor=ColorTranslator.FromHtml("Black");
mygrid.Font.Size=9;
mygrid.Font.Name="宋体";
mygrid.AllowSorting=true;
///sort命令的事件处理器
//mygrid.SortComm