ASP.NET实现在服务器控制网页

 动态添加控件:
  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;
   }
  }

动态添加控件GataGrid:
  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();
  }

1
服务器控件的动态添加和删除:
  private void Page_Load(object sender, System.EventArgs e)
  {
   if (!IsPostBack)
    Session["count"] = 1;
   ShowControl();
  }
   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;
   };
  }


利用Table动态添加控件
  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();
   } 
  }
  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 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>"}
}
  private void Page_Load(object sender, System.EventArgs e)
  {
   btn.Attributes["onclick"]= "javascript:alert('客户端事件!!');";   
  }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值