asp.net動態的生成,刪除table的行,主要是在后台動態創建單元行,單元表格,效果圖:


2.代碼:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="releaseAffair.aspx.cs" Inherits="affair_releaseAffair" %>
<!DOCTYPE html>
<!--發布事務頁面:名稱AffairName,內容content,創建日期-->
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td>
發布個人事務
</td>
</tr>
<tr>
<td>
事務名稱:<asp:TextBox runat="server" ID="text_affairName"></asp:TextBox>
</td>
</tr>
<tr>
<td>
事務內容:<asp:TextBox runat="server" ID="text_affairContent" TextMode="MultiLine" Width="500px" Height="100px"></asp:TextBox>
</td>
</tr>
</table><br />
<asp:Table ID="tableTarget" runat="server" Width="100%" CellSpacing="0" CaptionAlign="Bottom" CellPadding="2" >
</asp:Table>
<div>
<asp:Button runat="server" ID="btnAddRow" Text="添加" OnClick="btnAddRow_Click"/>
<asp:Button runat="server" ID="btnDelRow" Text="刪除" OnClick="btnDelRow_Click" />
<asp:Button runat="server" ID="btnSave" Text="保存" OnClick="btnSave_Click" />
</div>
</div>
</form>
</body>
</html>
后台代碼:
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class affair_releaseAffair : System.Web.UI.Page
{
Sqlhelper sp = null;
SqlDataReader dr = null;
SqlCommand comm = null;
protected void Page_Load(object sender, EventArgs e)
{
if (Session["username"] != null)
{
if (ViewState["count"] != null)
{
//每次刷新都重新建立表格循環再次添加行
for (int i = 0; i < Convert.ToInt16(ViewState["count"])/2; i++)
{
AddRows(tableTarget);
}
}
}
else {
Response.Write("<script>alert('請先登錄!')</script>");
// Server.Transfer("~/login.aspx");
Response.Write("<script>top.window.location.href = '../login.aspx?r='+Math.random() ;</script>");
//Response.Write("<script>window.location='../login.aspx';</script>");
//Response.Redirect("~/login.aspx",true);
}
}
// 刪除按鈕事件,總是默認刪除表的最后一行
protected void btnDelRow_Click(object sender, EventArgs e)
{
tableTarget.Rows.RemoveAt(tableTarget.Rows.Count - 1);
tableTarget.Rows.RemoveAt(tableTarget.Rows.Count - 1);
ViewState["count"] = Convert.ToInt16(ViewState["count"]) - 2;
}
protected void btnAddRow_Click(object sender, EventArgs e)
{
AddRows(tableTarget);
ViewState["count"] = Convert.ToInt16(ViewState["count"]) + 2; //記錄的table行數。
}
/// <summary>
///table中有8列,四列label,三列是TextBox一列是DropDownList,這是一個添加行的函數
///給表table1添加兩行
/// </summary>
/// <param name="table"></param>
public void AddRows(Table table) {
TableRow tr0 = new TableRow();
TableCell tc = new TableCell();
Label lb0 = new Label();
lb0.Text = "指標內容:";
lb0.Width = Unit.Parse("80px");
tc.Controls.Add(lb0); tc.Width = Unit.Parse("80px");
TableCell tc0 = new TableCell();
TextBox tb0 = new TextBox();
tb0.ID = "tbc" + table.Rows.Count; //content指標內容
tb0.TextMode = TextBoxMode.MultiLine; //多行
tb0.Width = Unit.Parse("400px");
tb0.Height = Unit.Parse("50px");
tc0.Controls.Add(tb0);
tc0.ColumnSpan = 7;
tr0.Cells.Add(tc);
tr0.Cells.Add(tc0);
table.Rows.Add(tr0);
TableRow tr = new TableRow();
for (int i = 1; i <= 3; i++) {
TableCell tc1 = new TableCell();
Label lb1 = new Label();
lb1.Text = "指標"+i+":";
lb1.Width= Unit.Parse("50px");
tc1.Controls.Add(lb1); tc1.Width = Unit.Parse("50px");
TableCell tc2 = new TableCell();
TextBox tb1 = new TextBox();
tb1.ID = "tb"+i+""+ table.Rows.Count;
tb1.TextMode = TextBoxMode.MultiLine;
tb1.Width = Unit.Parse("300px");
tc2.Controls.Add(tb1);
tr.Cells.Add(tc1);
tr.Cells.Add(tc2);
}
TableCell tc7 = new TableCell();
Label lb4 = new Label(); lb4.Width = Unit.Parse("80px");
lb4.Text = "您的選擇:";
tc7.Controls.Add(lb4); tc7.Width = Unit.Parse("80px");
TableCell tc8 = new TableCell();
DropDownList dpl = new DropDownList();
dpl.ID = "dpl" + table.Rows.Count;
for (int i = 1; i < 4; i++) dpl.Items.Add(i.ToString());
tc8.Controls.Add(dpl);
tr.Cells.Add(tc7);
tr.Cells.Add(tc8);
table.Rows.Add(tr);
table.Attributes.Add("border", "1");
}
//保存選中的值,保存到數據庫
protected void btnSave_Click(object sender, EventArgs e)
{
int num = saveAffair();
if (num == 1)
{//成功
Response.Write("<script>alert('添加成功!')</script>");
}
else {
Response.Write("<script>alert('添加失敗!')</script>");
}
}
//保存事務
public int saveAffair() {
String content,affairName,sqlStr;
int affairId=0,userId = getUserId(),num2=0;
SqlDataReader dr = null;
affairName = text_affairName.Text.Trim();
content = text_affairContent.Text.Trim();
if (affairName.Equals("") || content.Equals(""))
{
Response.Write("<script>alert('請輸入事務!')</script>");
}
else {
num2 = 1;
sp = Sqlhelper.getSqlhelper();
comm = sp.getComm();
sqlStr = "insert into affair(UserId,Content,AffairName,createDate) values("+ userId + ",'"+ content + "','"+ affairName + "',GETDATE());";
try
{
comm.CommandText = sqlStr;
int num = comm.ExecuteNonQuery();
sqlStr = "select * from affair order by id desc;";
comm.CommandText = sqlStr;
dr = comm.ExecuteReader();
if (dr.HasRows == true)
{
dr.Read();
affairId = Convert.ToInt32(dr["Id"].ToString());
}
dr.Close();
if (affairId > 0)
saveTarget(affairId, comm);//保存指標
}
catch (Exception ee)
{
num2 = 2;
throw;
}
finally {
sp.Close();
}
}//else
return num2;
}
//保存指標
public int saveTarget(int affairId,SqlCommand comm) {
String content="", select1="", select2="", select3="", answer,sqlStr="";
int num=0;
for (int i = 0; i < tableTarget.Rows.Count; i++)
{
if (i % 2 == 0)
{ //content內容
content = ((TextBox)tableTarget.Rows[i].FindControl("tbc" + i)).Text.Trim();
}
else
{//選項
select1 = ((TextBox)tableTarget.Rows[i].FindControl("tb1" + i)).Text.Trim();
select2 = ((TextBox)tableTarget.Rows[i].FindControl("tb2" + i)).Text.Trim();
select3 = ((TextBox)tableTarget.Rows[i].FindControl("tb3" + i)).Text.Trim();
answer = ((DropDownList)tableTarget.Rows[i].FindControl("dpl" + i)).SelectedValue;
if(!content.Equals(""))
sqlStr = "insert into "+"target"+ creatRandom() + " values("+ affairId + ",'"+ content + "','"+ select1 + "','"+
select2 + "','"+ select3 + "','"+ answer + "');";
}
if (!sqlStr.Equals("")|| !select1.Equals("")|| !select2 .Equals("")|| !select3.Equals("")) {
comm.CommandText = sqlStr;
num = comm.ExecuteNonQuery();
}
}
return num;
}
public int creatRandom() {
//第二種方法可以指定一個int型參數作為隨機種子:
long tick = DateTime.Now.Ticks;
Random ran = new Random((int)(tick & 0xffffffffL) | (int)(tick >> 32));
// 而下面這段代碼則指定返回值必須在50 - 100的范圍之內:
int iResult;
int iUp = 20;
int iDown = 1;
iResult = ran.Next(iDown, iUp);
return iResult;
}
public int getUserId() {
int userId=0;
sp = Sqlhelper.getSqlhelper();
comm = sp.getComm();
String username = Session["username"].ToString();
String sqlStr = "select Id from userInfo where Name='"+ username+"'";
comm.CommandText = sqlStr;
try
{
userId = (int)comm.ExecuteScalar();
}
catch (Exception)
{
throw;
}
return userId;
}
}
核心代碼:
/// <summary>
///table中有8列,四列label,三列是TextBox一列是DropDownList,這是一個添加行的函數
///給表table1添加兩行
/// </summary>
/// <param name="table"></param>
public void AddRows(Table table) {
TableRow tr0 = new TableRow();
TableCell tc = new TableCell();
Label lb0 = new Label();
lb0.Text = "指標內容:";
lb0.Width = Unit.Parse("80px");
tc.Controls.Add(lb0); tc.Width = Unit.Parse("80px");
TableCell tc0 = new TableCell();
TextBox tb0 = new TextBox();
tb0.ID = "tbc" + table.Rows.Count; //content指標內容
tb0.TextMode = TextBoxMode.MultiLine; //多行
tb0.Width = Unit.Parse("400px");
tb0.Height = Unit.Parse("50px");
tc0.Controls.Add(tb0);
tc0.ColumnSpan = 7;
tr0.Cells.Add(tc);
tr0.Cells.Add(tc0);
table.Rows.Add(tr0);
TableRow tr = new TableRow();
for (int i = 1; i <= 3; i++) {
TableCell tc1 = new TableCell();
Label lb1 = new Label();
lb1.Text = "指標"+i+":";
lb1.Width= Unit.Parse("50px");
tc1.Controls.Add(lb1); tc1.Width = Unit.Parse("50px");
TableCell tc2 = new TableCell();
TextBox tb1 = new TextBox();
tb1.ID = "tb"+i+""+ table.Rows.Count;
tb1.TextMode = TextBoxMode.MultiLine;
tb1.Width = Unit.Parse("300px");
tc2.Controls.Add(tb1);
tr.Cells.Add(tc1);
tr.Cells.Add(tc2);
}
TableCell tc7 = new TableCell();
Label lb4 = new Label(); lb4.Width = Unit.Parse("80px");
lb4.Text = "您的選擇:";
tc7.Controls.Add(lb4); tc7.Width = Unit.Parse("80px");
TableCell tc8 = new TableCell();
DropDownList dpl = new DropDownList();
dpl.ID = "dpl" + table.Rows.Count;
for (int i = 1; i < 4; i++) dpl.Items.Add(i.ToString());
tc8.Controls.Add(dpl);
tr.Cells.Add(tc7);
tr.Cells.Add(tc8);
table.Rows.Add(tr);
table.Attributes.Add("border", "1");
}
