asp.net实现动态添加table行

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");

    }

  

时间: 2024-10-13 12:22:50

asp.net实现动态添加table行的相关文章

miniUI 动态添加table - JS

1.效果展示 ↓ 2.具体代码 1 <script type="text/javascript"> 2 function addRow() { 3 var form = document.getElementById("addForm"); 4 var table = document.getElementById("table_Records"); 5 var id_com = form.getElementsByTagName(&

Jquery 实现动态添加table tr 和删除tr 以及checkbox的全选 和 获取添加TR删除TR后的数据

关于jquery实现动态添加table tr的问题我也不多说了 上面代码很多地方都有注释的 关于返回的 编辑后的table 数据 我这里想说的是我直接把他保存成一个连接起来的字符串了 格式 str=XXX | XXX | XXX , XXX | XXX | XXX , XXX | XXX | XXX 你也可以保存成对象类型的  我是为了方便后台的操作才这样做的 话不多说直接代码: <html> <head> <meta http-equiv="Content-Typ

C# DataGridView控件动态添加新行

C# DataGridView控件动态添加新行 DataGridView控件在实际应用中非常实用,特别需要表格显示数据时.可以静态绑定数据源,这样就自动为DataGridView控件添加相应的行.假如需要动态为DataGridView控件添加新行,方法有很多种,下面简单介绍如何为DataGridView控件动态添加新行的两种方法: 方法一: int index=this.dataGridView1.Rows.Add(); this.dataGridView1.Rows[index].Cells[

C# DataGridView控件 动态添加新行

DataGridView控件在实际应用中非常实用,特别需要表格显示数据时.可以静态绑定数据源,这样就自动为DataGridView控件添加相应的行.假如需要动态为DataGridView控件添加新行,方法有很多种,下面简单介绍如何为DataGridView控件动态添加新行的两种方法: 方法一: int index=this.dataGridView1.Rows.Add(); this.dataGridView1.Rows[index].Cells[0].Value = "1"; thi

Jquery动态插入table行

想在一个<table id="table1"></table>标签中动态的插入行,在jquery中可以这样做: $("#table1").append(str);//这里的str是一个字符串,字符串的内容html格式.如"<tr><td>测试1</td><td>测试2</td><td>测试3</td><td>测试4</td>&

ASP.NET页面动态添加脚本

????有时我们需要生成自己的JavaScript代码并在运行时动态添加到页面,接下来我们来看一下如何将生成的JavaScript代码动态添加到ASP.NET页面. ????为了添加脚本,要将自定义的脚本在一个字符串内或指向该脚本的文件中定义,之后调用ClientScriptManager类的方法注册脚本 方法一: string script = "<script>alert("Hello");</script>"; Page.ClientS

ASP.NET 网页动态添加客户端脚本

在System.Web.UI.Page类中包含了RegisterStarupScript()和RegisterClientScriptBlock()两个方法,使用这两个方法可以实现向Web页面动态添加脚本块,客户端脚本按运行方式可以分为两类:一类是在加载页面后立即运行,另一类是在发生客户端事件后才运行.前者的常见示例是打开页面时立即弹出一个广告条;后者的常见示例是当用户单击莫按钮时弹出一个消息框.RegisterStartupScript()和RegisterClientScriptBlock(

GridView动态添加新行

gridview动态添加行的原理就是用datatable增加新列然后重新绑定: 设计源码 设计gridview代码: <form id="form1" runat="server"> <div> <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> <asp:TextBox ID="TextBox2&qu

js动态添加table 数据tr td

成果库修改:      要求主题列表随成果类型改变而改变      网上查询资料后开工,在成果类型下拉框添加change()事件触发Dwr,查询主题集合——动态创建/编辑Table      概要代码如下: Jsp页面[javascript]//动态获取主题数据 function getzts(){     parentId = document.getElementById("bselect1").value;     if(parentId!=""){