-1

I am trying to add table rows in asp table but could not solve it.

I am trying to add new row on button click but it's generating on button click but on post back it disappears. How can i bind asp table so that it'll remain in table.

Here is my code-

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();
    }
}

Please help me.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Azhar Shahid
  • 151
  • 1
  • 4
  • 23

2 Answers2

3

This is because data needs to add to the table after you click on add button. I have slightly changed your code as follows

New method to add rows to the table(remove some part of your cord from the btnSave_Click event to this new method.

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

Also you need to call to this method at the end of btnSave_Click as follows

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 = "";
        }

finally BindTable() method is as follows

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

            BindTable();
        } 

that's all you need to do.. hope this will help you out..

Cheers Happy Coding....!!!

Shanaka Rathnayaka
  • 2,462
  • 1
  • 23
  • 23
0

It's cuz your table lost it state after postback. You can read about maintaining state of object in http://msdn.microsoft.com/en-us/library/ms972976.aspx. Basically all you need to do is something like this:

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;

}

Than all you need is to add _rows = tblLanguages.Rows at the end of you btnSave_Click method. Ofc you don't need to use ViewState and you could query your database in DataBind function to pull saved rows and then bind them to your table. View state just helps you to maintain object state between postbacks without need to query your database every time. You should be aware that you will need to add some code querying your database on the first load of a page to fill out initial state of your languages table.

Lesmian
  • 3,932
  • 1
  • 17
  • 28