在后代码里创建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;
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.SortCommand += new DataGridSortCommandEventHandler(Sort_Grid);
///设置headerstyle
mygrid.HeaderStyle.BackColor=ColorTranslator.FromHtml("Gold");
mygrid.HeaderStyle.ForeColor=ColorTranslator.FromHtml("Black");
mygrid.HeaderStyle.Font.Name="宋体";
mygrid.HeaderStyle.Font.Size=9;
mygrid.HeaderStyle.Font.Bold=true;
mygrid.HeaderStyle.HorizontalAlign=HorizontalAlign.Center;
///设置alternating style
mygrid.AlternatingItemStyle.BackColor=ColorTranslator.FromHtml("Silver");
mygrid.AlternatingItemStyle.ForeColor=ColorTranslator.FromHtml("Black");
///设置itemstyle
mygrid.ItemStyle.HorizontalAlign=HorizontalAlign.Left;
///创建绑定列和属性
BoundColumn FirstName = new BoundColumn();
BoundColumn LastName = new BoundColumn();
BoundColumn HomePhone = new BoundColumn();
BoundColumn Title = new BoundColumn();
FirstName.HeaderText="名字";
FirstName.DataField="FirstName";
FirstName.SortExpression="FirstName";
LastName.HeaderText="姓";
LastName.DataField="LastName";
LastName.SortExpression="LastName";
HomePhone.HeaderText="电话";
HomePhone.DataField="HomePhone";
HomePhone.SortExpression="HomePhone";
Title.HeaderText="职务";
Title.DataField="Title";
Title.SortExpression="Title";
mygrid.Columns.AddAt(0, FirstName);
mygrid.Columns.AddAt(1, LastName);
mygrid.Columns.AddAt(2, HomePhone);
mygrid.Columns.AddAt(3, Title);
///设置模板列属性和ItemStyle模板
tm.HeaderText="**删除信息**";
tm.HeaderStyle.HorizontalAlign=HorizontalAlign.Center;
tm.ItemStyle.BackColor = ColorTranslator.FromHtml("#FFF778");
tm.ItemStyle.HorizontalAlign=HorizontalAlign.Center;
///创建列模板。
///列模板从ITemplate继承
tm.ItemTemplate = mycol;
mygrid.Columns.AddAt(4, tm);
///绑定和返回
mygrid.DataSource = CreateDataSource();
mygrid.DataBind();
return mygrid;
}
}
/// ColumnTemplate 从ITemplate继承。
/// "InstantiateIn"定义子控件的属于谁
public class ColumnTemplate : ITemplate
{
public void InstantiateIn(Control container)
{
Label myLabel = new Label();
myLabel.Text="点击删除";
CheckBox mycheckbox = new CheckBox();
container.Controls.Add(myLabel);
container.Controls.Add(mycheckbox);
}
}
}