Panel控件
• Panel是一个服务器端的Web表单控件,一
个Panel控件就是HTML网页上的一个矩形
区域,它是否可见可以在服务器端进行控
制。因此,首先,我们可以从将HTML代码
段放在一个Panel控件中,HTML代码段可
以由服务器端控件和客户端控件组成。一
旦我们将Panel控件的visibility属性设置为
“false”,则整个HTML代码段就成为不可见
的了
private void btnNext_Click(object sender, System.EventArgs e)
        
{
            Panel mypanel;
            
string panelname;

            panelname 
= "Panel" + Session["currentpage"];
            mypanel 
= (Panel)FindControl(panelname);
            mypanel.Visible 
= false;

            
int currentpage = (int)Session["currentpage"];
            currentpage 
+= 1;
            Session[
"currentpage"= currentpage;
            panelname 
= "Panel" + Session["currentpage"];
            mypanel 
= (Panel)FindControl(panelname);
            mypanel.Visible 
=true;

        }


        
private void btnPrev_Click(object sender, System.EventArgs e)
        
{
            Panel mypanel;
            
string panelname;
 
            panelname 
= "Panel" + Session["currentpage"];
            mypanel 
= (Panel)FindControl(panelname);
            mypanel.Visible 
= false;

            
int currentpage = (int)Session["currentpage"];
            currentpage 
-= 1;
            Session[
"currentpage"= currentpage;
            panelname 
= "Panel" + Session["currentpage"];
            mypanel 
= (Panel)FindControl(panelname);
            mypanel.Visible 
= true;

        }

服务器控件的动态添加
PlaceHolder :
• 控件的容器!!
• 它使你可以将空容器控件放置到页内,
然后在运行时动态添加、移除或依次通
过子元素。该控件只呈现其子元素;它
不具有自己的基于HTML 的输出
private void Page_Load(object sender, System.EventArgs e)
        
{
            
// ÔÚ´Ë´¦·ÅÖÃÓû§´úÂëÒÔ³õʼ»¯Ò³Ãæ
            if ((ViewState["AddControl"]!= null&& ((bool)ViewState["AddControl"])) 
            
{
                phMain.Controls.Clear(); 
                
//Ìí¼Ó±êÇ©
                Label lb = new Label();
                lb.Text 
= "ÇëÑ¡ÔñÓû§ÐÕÃû!"+"<br>";
                phMain.Controls.Add(lb);
                DropDownList ddl 
= new DropDownList(); 
                ddl.ID
="controlID"
                ddl.AutoPostBack 
= true;
                phMain.Controls.Add(ddl);
            }

            
else
            
{
                phMain.Controls.Clear(); 
                
//Ìí¼Ó±êÇ©
                Label lb = new Label();
                lb.Text 
= "ÇëÑ¡ÔñÓû§ÐÕÃû!"+"<br>";
                phMain.Controls.Add(lb);
                DropDownList ddl 
= new DropDownList(); 
                ddl.ID
="controlID"
                ddl.AutoPostBack 
= true;
                
//phMain.Controls.Add(ddl);
                ddl.Width=200
                
string strConn = ConfigurationSettings.AppSettings["DSN"];            
                
string strSQL = "Select Username from tbUserInfo";//Select²éѯÓï¾ä
                SqlConnection myCn = new SqlConnection(strConn);            
                
try
                
{
                    myCn.Open();
                    SqlDataAdapter sda 
= new SqlDataAdapter(strSQL,myCn);
                    DataSet ds 
= new DataSet("ds");
                    sda.Fill(ds,
"Item");
                    ddl.DataSource 
= ds.Tables["Item"].DefaultView;
                    ddl.DataTextField 
= "UserName";
                    ddl.DataBind();
                    phMain.Controls.Add(ddl);
            
                }

                
catch(System.Data.SqlClient.SqlException ee)
                
{                
                    
throw new Exception(ee.Message);
                }

                
finally
                
{
                    myCn.Close();
                }

                ViewState[
"AddControl"= true


            }

        }


服务器控件的动态添加
Panel :
• Panel 控件是其他控件的容器。
• 如果打算以编程方式生成多个控件或者
打算隐藏/显示一组控件,此控件尤其有
用。
private void Page_Load(object sender, System.EventArgs e)
        
{
            CreateDataGrid();
        }

        
private void CreateDataGrid()
        
{

            Panel pnMain 
= new Panel();
            pnMain.Style[
"Position"]="Absolute";
            pnMain.Style[
"Top"]="30px";
            pnMain.Style[
"Left"]="100px";
            pnMain.Style[
"Width"]="500px";
            pnMain.Style[
"Height"]="300px";
            pnMain.Style[
"OVERFLOW"]="auto";//PanelµÄ´óС²»ËæDataGridµÄ´óС·¢Éú±ä»¯
            this.Controls.Add(pnMain);        
            
            DataGrid myDataGrid
=new DataGrid();

            BoundColumn s1
=new BoundColumn();
            s1.DataField
="EmployeeID";
            s1.HeaderText
="¹ÍÔ±ID";
            myDataGrid.Columns.Add(s1);


            BoundColumn s2
=new BoundColumn();
            s2.DataField
="LastName";
            s2.HeaderText
="ÐÕ";
            myDataGrid.Columns.Add(s2);


            BoundColumn s3
=new BoundColumn();
            s3.DataField
="FirstName";
            s3.HeaderText
="Ãû";
            myDataGrid.Columns.Add(s3);


            BoundColumn s4
=new BoundColumn();
            s4.DataField
="Title";
            s4.HeaderText
="±êÌâ";
            myDataGrid.Columns.Add(s4);


            BoundColumn s5
=new BoundColumn();
            s5.DataField
="BirthDate";
            s5.HeaderText
="ÉúÈÕ";
            myDataGrid.Columns.Add(s5);


            BoundColumn s6
=new BoundColumn();
            s6.DataField
="Address";
            s6.HeaderText
="µØÖ·";
            myDataGrid.Columns.Add(s6);

            myDataGrid.Style[
"Position"]="Absolute";
            myDataGrid.Style[
"Left"]="0px";
            myDataGrid.Style[
"Top"]="0px";


            myDataGrid.BorderColor
=Color.FromName("#DEBA84");
            myDataGrid.BackColor
=Color.FromName("#DEBA84");
            myDataGrid.Style[
"BorderStyle"]="None";
            myDataGrid.Attributes.Add(
"BorderStyle","None");


            myDataGrid.CellPadding
=3;
            myDataGrid.CellSpacing
=2;
            myDataGrid.Attributes.Add(
"BorderWidth","1px");
            myDataGrid.PageSize
=2;
            myDataGrid.AutoGenerateColumns
=true;


            myDataGrid.SelectedItemStyle.Font.Bold
=true;
            myDataGrid.SelectedItemStyle.ForeColor
=Color.White;
            myDataGrid.SelectedItemStyle.BackColor
=Color.FromName("#738A9C");


            myDataGrid.ItemStyle.ForeColor
=Color.FromName("#8C4510");
            myDataGrid.ItemStyle.BackColor
=Color.FromName("#FFF7E7");
            myDataGrid.ItemStyle.HorizontalAlign
=HorizontalAlign.Center;

            myDataGrid.ItemStyle.Wrap
=false;


            myDataGrid.HeaderStyle.Font.Bold
=true;
            myDataGrid.HeaderStyle.ForeColor
=Color.White;
            myDataGrid.HeaderStyle.BackColor
=Color.FromName("#A55129");
            myDataGrid.HeaderStyle.HorizontalAlign
=HorizontalAlign.Center;
            myDataGrid.HeaderStyle.Wrap
=false;


            myDataGrid.AutoGenerateColumns
=false;
            myDataGrid.HorizontalAlign
=HorizontalAlign.Center;


            myDataGrid.PagerStyle.HorizontalAlign
=HorizontalAlign.Center;
            myDataGrid.PagerStyle.Wrap
=false;
            myDataGrid.Attributes.Add(
"style","word-break:keep-all;word-wrap:normal");


            pnMain.Controls.Add(myDataGrid);
//°ÑDataGridÌí¼Óµ½PanelÖÐ


            SqlConnection thisConnection
=new SqlConnection ("Data Source=(local);Initial Catalog=Northwind;UID=sa;PWD=111");
            SqlCommand thisCommand
=thisConnection.CreateCommand ();
            
try
            
{
                thisConnection.Open ();
            }

            
catch(Exception ex)
            
{
                thisConnection.Close ();
            }

            thisCommand.CommandText 
="select * from employees";
            SqlDataReader sqlDataReader;
            sqlDataReader
=thisCommand.ExecuteReader ();
            myDataGrid.DataSource 
=sqlDataReader;


            myDataGrid.DataBind();
            sqlDataReader.Close();
        }

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace ServerSideControl
{
    
/// <summary>
    
/// WebForm1 µÄժҪ˵Ã÷¡£
    
/// </summary>

    public class WebForm1 : System.Web.UI.Page
    
{
        
protected System.Web.UI.WebControls.Button btnAdd;
        
protected System.Web.UI.WebControls.Button btnDel;
        
protected System.Web.UI.WebControls.Panel pnMain;
    
        
private void Page_Load(object sender, System.EventArgs e)
        
{
            
if (!IsPostBack)
                Session[
"count"= 1;
            ShowControl();
        }


        
Web Form Designer generated code

        
private void btnAdd_Click(object sender, System.EventArgs e)
        
{
            Session[
"count"= (int)Session["count"+1
            ShowControl();
        }


        
private void btnDel_Click(object sender, System.EventArgs e)
        
{
            Session[
"count"= (int)Session["count"-1
            ShowControl();
            
        }

        
private void ShowControl()
        
{
            textBoxArray tba 
= new textBoxArray(pnMain);
            
int nCount = (int)Session["count"];
            pnMain.Controls.Clear();
            
for(int i=1;i<=nCount;i++)
                tba.addNewTextBox();
        }

    }

    
//************************** 
    
//ÀàtextBoxArrayʵÏÖÁ˶¯Ì¬Ôö¼ÓºÍɾ³ý 
    
//textBoxµÄ¹¦ÄÜ 
    
//************************** 
    public class textBoxArray:System.Collections.CollectionBase 
    

        
private readonly System.Web.UI.Control HostPage;
        
//¹¹Ô캯Êý 
        public textBoxArray(System.Web.UI.Control Host) 
        

            HostPage
=Host; 
        }
 
        
//addNewTextBox·½·¨Ìí¼ÓÒ»¸ötextbox¿Ø¼þ 
        public void addNewTextBox() 
        

            
//this.List.Add(this.Count.ToString());

            
//½¨Ò»¸öеÄtextboxʵÀý. 
            TextBox aTextBox=new TextBox(); 
            
//½«ÆäÌí¼Óµ½¼¯ºÏµÄÄÚ²¿Áбí 
            this.List.Add(aTextBox); 
            
//½«TextBoxÌí¼Óµ½ÓÉHostForm×Ö¶ÎÒýÓõĴ°ÌåµÄ¼¯ºÏÁбíÖР
            HostPage.Controls.Add(aTextBox); 
            
//ÉèÖóõʼÊôÐÔ 
            aTextBox.Style["Left"]=Convert.ToString((Count-1)*130+70); 
            aTextBox.Style[
"Top"= Convert.ToString(160);
            aTextBox.Width
=120
            aTextBox.BorderStyle
=BorderStyle.Outset;
            aTextBox.ID
=this.Count.ToString(); 
            
//³õʼֵ 
            aTextBox.Text="TextBoxʾÀý"
            aTextBox.ForeColor
=System.Drawing.Color.Blue; 
            
            
        }
 
        
//´´½¨Ë÷Òý 
        public TextBox this [int index] 
        

            
get 
            

                
return (TextBox)this.List[index]; 
            }
 
        }
 
        
//Remove·½·¨ÓÃÀ´É¾³ý¿Ø¼þ 
        public void Remove() 
        

            
if(this.Count>0
            

                HostPage.Controls.Remove (
this[this.Count -1]); 
                
this.List.RemoveAt(this.Count-1); 
            }
 
        }
 
    }


}



        
private void Page_Load(object sender, System.EventArgs e)
        
{
            Button Button1 
= new Button();
            Button1.CommandArgument 
= "b1";
            Button1.Text 
= "Btn1";
            Button1.Command 
+= new CommandEventHandler(this.OnButton); 
            PlaceHolder1.Controls.Add(Button1); 
            Button Button2 
= new Button();
            Button2.CommandArgument 
= "b2";
            Button2.Text 
= "Btn2";
            Button2.Command 
+= new CommandEventHandler(this.OnButton); 
            PlaceHolder1.Controls.Add(Button2); 


            Control c3 
= ParseControl("<asp:Button id='Button3' text='Btn3' commandname='Btn' commandargument='b3' runat='server' />"); 
            Control c4 
= ParseControl("<asp:Button id='Button4' text='Btn4' commandname='Btn' commandargument='b4' runat='server' />"); 
            PlaceHolder1.Controls.Add(c3); 
            PlaceHolder1.Controls.Add(c4); 
            Button myBut 
= (Button)Page.FindControl("Button3"); 
            myBut.Command 
+= new CommandEventHandler(this.OnButton); 
            Button myBut2 
= (Button)Page.FindControl("Button4"); 
            myBut2.Command 
+= new CommandEventHandler(this.OnButton); 

        }

        
public void OnButton(Object Sender, CommandEventArgs e) 
        

            
switch (e.CommandArgument.ToString().ToLower()) 
            

                
case "b1"
                    Label1.Text 
= "Button 1"
                    
break
                
case "b2"
                    Label1.Text 
= "Button 2"
                    
break
                
case "b3"
                    Label1.Text 
= "Button 3"
                    
break
                
case "b4"
                    Label1.Text 
= "Button 4"
                    
break
            }

        }
 

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace ServerSideControl
{
    
/// <summary>
    
/// AddInTable 的摘要说明。
    
/// </summary>

    public class AddInTable : System.Web.UI.Page
    
{
        
protected System.Web.UI.WebControls.Table Table1;
        
protected System.Web.UI.WebControls.PlaceHolder PlaceHolder1;
        
protected System.Web.UI.WebControls.Button btnAdd;
    
        
private void Page_Load(object sender, System.EventArgs e)
        
{
            
if(ViewState["Count"]!=null
            

                
for(int i=0;i<Convert.ToInt16(ViewState["Count"]);i++
                    AddTextBoxs(); 
                AddButton(); 
            }
 

        }


        
Web Form Designer generated code

        
private void btnAdd_Click(object sender, System.EventArgs e)
        
{
            AddTextBoxs(); 
            
if(ViewState["Count"]==null)
                AddButton(); 
            ViewState[
"Count"]=Convert.ToInt16(ViewState["Count"])+1
        }

        
private void AddTextBoxs() 
        

            TableRow tr
=new TableRow(); 
            TableCell tc1
=new TableCell(); 
            TextBox t
=new TextBox(); 
            t.ID
="tb"+Table1.Rows.Count; 
            tc1.Controls.Add(t); 
            TableCell tc2
=new TableCell(); 
            DropDownList dpl
=new DropDownList(); 
            dpl.ID
="dpl"+Table1.Rows.Count; 
            
for(int i=0;i<10;i++)dpl.Items.Add(i.ToString()); 
            tc2.Controls.Add(dpl); 
            tr.Cells.Add(tc1); 
            tr.Cells.Add(tc2); 
            Table1.Rows.Add(tr); 
        }
 

        
private void AddButton() 
        
{         
            Button b
=new Button(); 
            b.ID
="btn"
            b.Text
="显示"
            b.Click 
+= new System.EventHandler(btn_Click); 
            PlaceHolder1.Controls.Add(b); 
        }
 
        
private void btn_Click(object sender, System.EventArgs e) 
        

            
for(int i=0;i<Table1.Rows.Count;i++
            

                Response.Write(((TextBox)Table1.Rows[i].FindControl(
"tb"+i)).Text+((DropDownList)Table1.Rows[i].FindControl("dpl"+i)).SelectedItem.Value+"<br>"); 
            }
 
        }
 
    }

}


动态添加HTML控件
• 客户端事件,与服务端事件是不同的,
客户端事件在服务端看来就是一种显示效
果而已。
• 服务端程序认为为控件添加一个样式信
息,和添加一个客户端事件是一样的。
    private void Page_Load(object sender, System.EventArgs e)
        
{
            btn.Attributes[
"onclick"]= "javascript:alert('¿Í»§¶Ëʼþ!!');";    

        }

private void InitializeComponent()
        
{    
            
this.btn.Click += new System.EventHandler(this.btn_Click);
            
this.Load += new System.EventHandler(this.Page_Load);

        }

        
#endregion

        
private void btn_Click(object sender, System.EventArgs e)
        
{
            Response.Write(
"<DIV style='DISPLAY: inline; Z-INDEX: 102; LEFT: 227px; WIDTH: 210px; COLOR: green; FONT-STYLE: italic; POSITION: absolute; TOP: 126px; HEIGHT: 64px; FONT-VARIANT: normal' ms_positioning='FlowLayout'>ÕâÊÇ¿Í»§¶Ëhtml£¡</DIV>");

        }
posted on 2006-06-05 15:28  公木子  阅读(478)  评论(0编辑  收藏  举报