用代码创建DataGrid的多链接及checkbox事件响应_.NET_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > .NET > 用代码创建DataGrid的多链接及checkbox事件响应

用代码创建DataGrid的多链接及checkbox事件响应

 2013/8/25 14:59:27  蒋叶湖  博客园  我要评论(0)
  • 摘要:本例用代码实现了创建DataGrid并响应了CheckBox事件,并实现了超链接列的多变量传送。创建一个前台页面CreateDataGrid.aspx:在Form中添加一个PlcaeHolder,ID为"ph",Runat="Server"后台页面CreateDatagrid.aspx.cspublicclassCreateDataGrid:System.Web.UI.Page...{publicStringsql="SelectFirstName,LastName,HomePhone
  • 标签:事件 创建 代码 tag
 

本例用代码实现了创建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.SortCommand += new DataGridSortCommandEventHandler(Sort_Grid);
            mygrid.ItemDataBound +=new DataGridItemEventHandler(mygrid_ItemDataBound);

            
///设置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;

            
///创建绑定列和属性

            HyperLinkColumn FirstName 
= new HyperLinkColumn();
            BoundColumn LastName 
= new BoundColumn();
            BoundColumn HomePhone 
= new BoundColumn();
            BoundColumn Title 
= new BoundColumn();

//            FirstName.HeaderText="名字";
//            FirstName.DataField="FirstName";
//            FirstName.SortExpression="FirstName";

            FirstName.HeaderText
="名字";
            
            FirstName.DataTextField 
="FirstName";
            FirstName.SortExpression
="FirstName";
            FirstName.NavigateUrl 
= "http://localhost/test.aspx";

            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;
            

            TemplateColumn aa
=new TemplateColumn();
            ColumnTemplate1 tt 
= new ColumnTemplate1();
            aa.ItemTemplate 
= tt;

            
            
///创建列模板。
            
///列模板从ITemplate继承

            tm.ItemTemplate = mycol;
            mygrid.Columns.AddAt(
4, tm);
            mygrid.Columns.AddAt(
5,aa);  

            
///绑定和返回
            mygrid.DataSource = CreateDataSource();
            mygrid.DataBind();
            
return mygrid;
        }


        
private void mygrid_ItemDataBound(object sender, DataGridItemEventArgs e)
        
{
            
if(e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            
{
                HyperLink link  
= (HyperLink)e.Item.Cells[0].Controls[0];  
                
string url = link.NavigateUrl;
    
//实现多参数链接
                url += "?id=" + e.Item.Cells[1].Text + "&id2=" + e.Item.Cells[2].Text;
                link.NavigateUrl 
= url;
            }

        }

    }

 
 



再添加关键的几段

 ///  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);
        }


    }
 


添加CheckBox事件:

public class ColumnTemplate1 : ITemplate
    
{

        
public void InstantiateIn(Control container)
        
{
            Label myLabel 
= new Label();
            myLabel.Text
="test";
            CheckBox lnk 
= new CheckBox();
            lnk.AutoPostBack 
= true;
            lnk.CheckedChanged 
+=new EventHandler(lnk_CheckedChanged);
            container.Controls.Add(myLabel);
            container.Controls.Add(lnk);
        }



        
private void lnk_CheckedChanged(object sender, EventArgs e)
        
{
            CheckBox lnk 
= (CheckBox)sender;
            DataGrid dg 
= (DataGrid)lnk.NamingContainer.NamingContainer;
            
if(dg == nullreturn;
             
//实现CheckBox事件响应
            DataGridItem di =(DataGridItem)lnk.NamingContainer;
            HyperLink lnkID= (HyperLink)di.Cells[0].Controls[0];
            string s2 =  lnkID.Text.Trim()+lnk.ID+"被选中了!"
;
        }

    }
发表评论
用户名: 匿名