在asp.net中的asp表中动态添加表行

时间:2014-05-01 06:37:24

标签: c# asp.net sql-server

我试图在asp表中添加表行但无法解决它。

我正在尝试在按钮点击上添加新行,但它会在按钮点击时生成,但在回发后它会消失。我如何绑定asp表,以便它保留在表中。

这是我的代码 -

Default.aspx的

<body>
<form id="form1" runat="server">
    <asp:Table ID="tblAdd" runat="server" BorderWidth="2">
        <asp:TableHeaderRow>
            <asp:TableHeaderCell ColumnSpan="2">
                Add Languages
            </asp:TableHeaderCell>
        </asp:TableHeaderRow>
        <asp:TableRow>
            <asp:TableCell>
                Name<font color="red">*</font>
            </asp:TableCell>
            <asp:TableCell>
                <asp:TextBox ID="txtName" runat="server" Width="200"></asp:TextBox>
            </asp:TableCell>
        </asp:TableRow>
        <asp:TableRow>
        <asp:TableCell>
        </asp:TableCell>
            <asp:TableCell><asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
                     ErrorMessage="Required" Display="Dynamic" ControlToValidate="txtName"
                     ForeColor="Red">
                </asp:RequiredFieldValidator></asp:TableCell>
        </asp:TableRow>
        <asp:TableRow>
            <asp:TableCell ColumnSpan="2">
                <hr />
            </asp:TableCell>
        </asp:TableRow>
        <asp:TableRow>
            <asp:TableCell Width="50">
                <asp:Button ID="btnSave" runat="server" Text="Save" OnClick="btnSave_Click" BackColor="#999966"  />
            </asp:TableCell>
            <asp:TableCell>
                <asp:Button ID="btnCancel" runat="server" Text="Cancel" OnClick="btnCancel_Click" BackColor="#999966"  CausesValidation="False" />
            </asp:TableCell>
        </asp:TableRow>
    </asp:Table>

    <asp:Label ID="Label1" runat="server" Text="<font color=red>*</font>Required Field" Font-Size="Small"></asp:Label>
    <div style="background-color:Aqua; width:500px; border-color:Red">
        <asp:Label ID="Label2" runat="server" Font-Size="X-Large"></asp:Label>
    </div>
    <br />
    <br />
    <asp:Table ID="tblLanguages" runat="server" BorderWidth="2">
            <asp:TableHeaderRow>
                <asp:TableHeaderCell ColumnSpan="2">
                    Languages
                </asp:TableHeaderCell>
            </asp:TableHeaderRow>
            <asp:TableRow>
                <asp:TableCell Width="20">
                    <asp:Button ID="btnAdd" runat="server" Text="Add" onclick="btnAdd_Click" BackColor="#999966" />
                </asp:TableCell>
                <asp:TableCell>
                    <asp:Button ID="btnDelete" runat="server" Text="Delete" onclick="btnDelete_Click" BackColor="#999966" />
                </asp:TableCell>
            </asp:TableRow>
            <asp:TableRow>
                <asp:TableCell BackColor="#FFE4B5">
                    <asp:CheckBox ID="checkbox1" runat="server" />
                </asp:TableCell>
                <asp:TableCell BackColor="#FFE4B5">
                    Name
                </asp:TableCell>
            </asp:TableRow>   
        </asp:Table> 
</form>

Default.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;

public partial class _Default : System.Web.UI.Page
{

    protected void Page_Load(object sender, EventArgs e)
    {
            tblAdd.Visible = false;
            Label1.Visible = false;
    }



    private void BindTable()
    {
        List<TableRow> testlist = new List<TableRow>();
        foreach (var item in testlist)
        {
            TableRow NewRow1 = new TableRow();
            TableCell NewCell1 = new TableCell();
            CheckBox newCheckBox = new CheckBox();

            NewCell1.Controls.Add(newCheckBox);
            NewRow1.Cells.Add(NewCell1);

            TableCell NewCell2 = new TableCell();

            Label newLable1 = new Label();
            newLable1.Text = txtName.Text;

            NewCell1.Controls.Add(newLable1);
            NewRow1.Cells.Add(NewCell1);
            tblLanguages.Rows.Add(NewRow1);
        }
    }

    protected void btnAdd_Click(object sender, EventArgs e)
    {
        tblAdd.Visible = true;
        btnAdd.Visible = false;
        btnDelete.Visible = false;
        Label1.Visible = true;
        Label2.Visible = false;

        BindTable();
    }

    protected void btnDelete_Click(object sender, EventArgs e)
    {

    }
    protected void btnCancel_Click(object sender, EventArgs e)
    {
         tblAdd.Visible = false;
         btnAdd.Visible = true;
         btnDelete.Visible = true;
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            btnAdd.Visible = true;
            btnDelete.Visible = true;
            Label2.Visible = true;
            tblAdd.Visible = false;
            Label2.Text = "Successfully Added";
            add();

            BindTable();
        }

        txtName.Text = "";
    }

    public int add()
    {
        string strcon = ConfigurationManager.ConnectionStrings["Dbconnection"].ConnectionString;
        SqlConnection sqlConnection = new SqlConnection(strcon);

        SqlCommand command = new SqlCommand("hrm_AddLanguages2", sqlConnection);
        command.CommandType = CommandType.StoredProcedure;
        command.Parameters.Add("@Name", SqlDbType.VarChar).Value = txtName.Text;
        command.Parameters.Add("@CreatedOn", SqlDbType.DateTime).Value = DateTime.Now;
        command.Parameters.Add("@UpdatedOn", SqlDbType.DateTime).Value = DateTime.Now;
        command.Parameters.Add("@CreatedBy", SqlDbType.BigInt).Value = 1;
        command.Parameters.Add("@UpdatedBy", SqlDbType.BigInt).Value = 1;
        command.Parameters.Add("@IsDeleted", SqlDbType.Bit).Value = 0;
        sqlConnection.Open();
        return command.ExecuteNonQuery();
    }
}

请帮帮我。

2 个答案:

答案 0 :(得分:3)

这是因为在您单击“添加”按钮后需要将数据添加到表中。我稍微更改了您的代码,如下所示

向表中添加行的新方法(从btnSave_Click事件中移除部分线缆到此新方法。

private void BindTable()
        {
            foreach (var item in testList)
            {
                TableRow NewRow1 = new TableRow();
                TableCell NewCell1 = new TableCell();
                CheckBox newCheckBox = new CheckBox();

                NewCell1.Controls.Add(newCheckBox);
                NewRow1.Cells.Add(NewCell1);

                TableCell NewCell2 = new TableCell();

                Label newLable1 = new Label();
                newLable1.Text = item.Name;

                NewCell1.Controls.Add(newLable1);
                NewRow1.Cells.Add(NewCell1);
                tblLanguages.Rows.Add(NewRow1);
            }
        }

此外,您需要在btnSave_Click结束时调用此方法,如下所示

protected void btnSave_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                btnAdd.Visible = true;
                btnDelete.Visible = true;
                Label2.Visible = true;
                tblAdd.Visible = false;
                Label2.Text = "Successfully Added";
                add();

                BindTable();
            }

            txtName.Text = "";
        }

最后BindTable()方法如下

protected void btnAdd_Click(object sender, EventArgs e)
        {
            tblAdd.Visible = true;
            btnAdd.Visible = false;
            btnDelete.Visible = false;
            Label1.Visible = true;
            Label2.Visible = false;

            BindTable();
        } 

这就是你需要做的一切..希望这会帮助你...

干杯 快乐的编码...... !!!

答案 1 :(得分:0)

这是因为你的桌子在回发后失去了状态。您可以在http://msdn.microsoft.com/en-us/library/ms972976.aspx中阅读有关维护对象状态的信息。基本上你需要做的就是这样:

protected List<TableRow> _rows
{
  get
  {
    List<TableRow> list = (List<TableRow>) ViewState["myRows"];
    if (list != null)
       return list;
    else
       return new List<TableRow>;
  }
  set
  {
    ViewState["myRows"] = value;
  }
}

private override void DataBind()
{
    tblLanguages.Rows = _rows;

}

您所需要的只是在btnSave_Click方法的末尾添加_rows = tblLanguages.Rows。 Ofc您不需要使用ViewState,您可以在DataBind函数中查询数据库以提取已保存的行,然后将它们绑定到您的表。视图状态只是帮助您维护回发之间的对象状态,而无需每次都查询数据库。您应该知道,您需要在第一次加载页面时添加一些查询数据库的代码,以填写语言表的初始状态。