Add row to table with table.row.add()

Everytime I click on a button I want to add a tableRow to a table like this:
        TextBox TB = new TextBox();
       
        TableCell Cell = new TableCell();
        Cell.Controls.Add(TB);

        TableRow Row = new TableRow();
        Row.Cells.Add(Cell);

        table.Rows.Add(Row);

It works the first time, but when I click the button again the last row is overwritten. Why, and how can I solve this? I want an easy way for the user to add more rows to a table. 

0
sweddotnet
11/25/2007 8:08:52 PM
asp.net.web-forms 93655 articles. 2 followers. Follow

13 Replies
525 Views

Similar Articles

[PageSpeed] 50

 

void btn_Click(sender, e)
{
        TextBox TB = new TextBox();
        
        TableCell Cell = new TableCell();
        Cell.Controls.Add(TB);

        TableRow Row = new TableRow();
        Row.Cells.Add(Cell);

        table.Rows.Add(Row);

        int rows = 0;
        if (ViewState["rows] != null)
               rows = (int)ViewState["rows];
        rows++;
        ViewState["rows] = rows;

}

void Page_Load(sender, e)
{
  if (ViewState["rows] != null)
  {
      int rows = (int)ViewState["rows];
      for (i = 1; i <= rows; i++)
      {
          // Create the textbox and add it to the row
      }
  }
}
 Golden rule about dynamic controls (controls that you add at runtime) is that you have to recreate them on each and every postback.  You somehow has to track (viewstate, hidden fields, session etc) how many rows have been added and add those on each page load.
0
codeasp
11/25/2007 8:32:04 PM

 Thanks for your help! Now I understand what I need to do.

 The thing is that I can't just add new rows, because the user can have written things in the textbox. So I must somehow get the old rows the user has added and then add the new row. How can I do that?
 

0
sweddotnet
11/25/2007 8:51:35 PM

The user entered values in text boxs will stay there.... as page postback processing will take place after page Load.... by the time it tries to renders values from form processing, you already created the required rows in load event.......  try yourself.....


Mark it as answer if you really think it helped you a bit.
Bob Lakkakula
http://nlakkakula.wordpress.com
0
Bobzee
11/25/2007 10:30:50 PM

Thanks for your help! 

I mean the textbox in the row that was created by the user, and as it will be overwritten it can't stay there or can it?

0
sweddotnet
11/25/2007 10:46:05 PM

I was talking about the textbox in dynamically created row too.... :-)


Mark it as answer if you really think it helped you a bit.
Bob Lakkakula
http://nlakkakula.wordpress.com
0
Bobzee
11/25/2007 10:54:50 PM

You just have to recreate the controls and viewstate will take care of the postback data for you (that is if you create the controls before or on page_load event).  As the previous poster has written asp.net take cares of the rest.  Try it yourself.

0
codeasp
11/26/2007 12:43:32 AM

 Thanks very much for your help! I finally got it working, my mistake!

 Now I can add and delete rows. I now want the user to click on a button to save the values in the textboxes inside the table. I'm trying to do this with this code but it doesn't seem to be working. It just takes the value of the first tablerow, but it takes this value as many times as there are rows in the table.

foreach (TableRow  row in table.Rows)
        {
            tb = row.Cells[0].FindControl("myTB") as TextBox;
            saveData(tb);
        }

 
I think I'm doing the same mistake as before, but I don't know how to fix it.

 Please help!

 

0
sweddotnet
11/27/2007 2:24:25 PM

What is the signature of your method saveData (I mean what kind of parameter does it accept)?  It might be better to send the Text inside the TextBox than sending the TextBox itself.  Post your saveData method here.

0
codeasp
11/27/2007 8:18:06 PM

I run this code when the insert command have been executed on my formview: 

protected void FV_X_Inserted(object sender, FormViewInsertedEventArgs e)
    {
        TextBox tb;
        Table table = FV_X.FindControl("Table") as Table;
        string sqlcommand = "";
        foreach (TableRow  row in table.Rows)
        {
            tb = row.Cells[0].FindControl("TB") as TextBox;
            sqlcommand += " INSERT INTO tbl (text) VALUES ('" + tb.Text + "'); ";
        }

         MySqlConnection Conn = new MySqlConnection(ConfigurationManager.ConnectionStrings["x"].ConnectionString);
        MySqlCommand Cmd = new MySqlCommand(sqlcommand, Conn);
        Cmd.Connection.Open();
        Cmd.ExecuteNonQuery();
        Cmd.Connection.Close();
        Cmd.Dispose();
        Conn.Dispose();

0
sweddotnet
11/28/2007 9:18:38 PM

Put a breakpoint in your code just after the foreach loop and observe the sqlcommand variable.  Check what is the value and if you have physical access to the Query Analyzer then run the query?  Does it run fine? 

0
codeasp
11/29/2007 1:09:30 AM

Hi again!

Yes, I tried this. It has added the querys but it only contains the value from the first TextBox in every query, even if I loop throught all cells. What can be wrong?


0
sweddotnet
11/29/2007 10:17:58 PM

 Anyone?

0
sweddotnet
12/1/2007 1:15:15 PM

I found it out myself I had to set TextBox.ID to different ID for every TextBox.

0
sweddotnet
12/2/2007 12:14:03 PM
Reply:

Similar Artilces:

Trying to append (add) row to table: row overwritten :(
 Hi, I was hoping someone could lend me a hand. I have a button and want to add one row to a table every time I click that button. The thing is, it works find the first time, but the second, third, ... the row is simply overwritten. Does anyone know what I'm doing wrong? I simply want to append a new row to the end of the table. This is the C# code:1 protected void Button1_Click(object sender, EventArgs e) 2 { 3 TableRow row = new TableRow(); 4 5 for (int i = 0; i < 5; ++i) 6 { 7 TableCell cell = new TableCell()...

How to add a footer row to a table after deleting all footer rows
I'm sure this is a very easy thing to do, but I can't figure out how to do it. I have a table, and I deleted all the footer rows.  Now I would like to add one footer row.  How do I do that? If I right-click on the detail row and select Insert Row Below, it is, of course, another detail row. I'm stumped -- thanks for any help you can give!Cynthia Do you have groups in your table?  You should be able to right click on any table row and toggle the corresponding menu item to show the table header, details or footer.  It is in the right click menu includ...

Add a row to table Dynamically for each click of Add Button
Dear All, I need to add one row to the existing table each time when I click Add button. I tried with the below code. It adds one row for the first click and for the next clicks it does nothing.. could you please recify where I am wrong? private void Button1_Click(object sender, System.EventArgs e){     int cnt = Convert.ToInt32(Session[COUNT]) + 1;    HtmlTableRow tRow1 = new HtmlTableRow();tRow1.ID = "rowID" + cnt;tblCR.Rows.Add(tRow1);HtmlTableCell tCel1 = new HtmlTableCell();tCel1.InnerText  = "aaa";tRow1.Cells....

add data from multiple rows in table to one row in gridview
 heya is there any way of adding data from multiple rows in table to one row in gridview. eg. ipc                 column 1 ,            2 ,                       3,                 4  1,    11111                 33                  &nbs...

Need to add a row of data in table B for each person listed in table A
I need to figure out how to do a "mass" insert into a sql table.   From Table A, I have each users USERID,  I need to grab that UserID and use it to insert a row into Table B with the new row containing the USERID and a Desc.  Here's how my data looks to do the select.. but how do I write the Insert?  (Select USERID from TableA) 71233 (Insert into TableB, USERID and Desc) USERID      DESC7                XXX12       ...

Is having a trigger that inserts a row in Table 'A', when a row in same table is inserted by ADo.Net code?
I want to insert a row for a Global user  in Table 'A' whenever ADO.Net code inserts a Local user row into same table. I recommended using a trigger to implement this functionality, but the DBA was against it, saying that stored proecedures should be used, since triggers are unreliable and slow down the system by placing unecessary locks on the table. Is this true OR the DBA is saying something wrong? My thinking is that Microsoft will never include triggers if they are unreliable and the DBA is just wanting to offload the extra DBA task of triggers to the programmer so that a s...

Update row in Table A from row in Table B
Hello, I have 2 tables.... table A and table B. Ok, In a stored procedure, I pass in an int value @ID I want to get the row from Table B WHERE ID =@ID....and then UPDATE the Row in Table A that has the same ID...with the values from table B. Table A ID | Col1 | Col2 ----------------------- 2 a a Table B ID | Col1 | Col2 ----------------------- 2 b b I would like to update A.Col1 with B.Col1 and A.Col2 with B.Col2 Can someone help me out with this syntax? Thanks a lot. update tableA ...

Update a rows in one table for each row in other table
Hello all, i am a newbie in SQL and i want to ask for your help in order to do the following update statement. I have a table tblUsers which holds all the users, one of the fields in their GroupId. In the UserGroup table i have a field "UsersCount" and in that field i want to keep the number of the users in that group. Basically i want everytime i am saving a user to recalculate the users in all usergroups. I am trying to have something like:SELECT User_GroupId, count(User_GroupId) as UsersCount FROM tblUsersWHERE DeletedFlag = 0 GROUP BY User_GroupId and then:"FOR EACH" User_GroupIdUPDAT...

Alter Table fails to add a new column to a table with 25 million rows
Hello, We use ALTER TABLE to add a new column to a table with about 25 million rows. This takes a long time and after about 3 hours it fails saying that it has run out of locks with an error code of C210. If anyone can help me, I would really appreciate it. TIA Regards, Mahesh Please show us the ALTER TABLE that is failing. We may be able to suggest an alternative ALTER TABLE followed by a cursor update loop where you can do periodic COMMITs. The problem is that ALTER TABLE will do all it's work in one transaction and acquire too many locks. If you had a page size of 8...

How to add rows to same table
I have a table of 5 columns (a snippet of the table is shown below). I need to copy the rows where the second column's GUID is for example C7E5BA40-54C9-11D7-83A0-0080C8FC6E95 into the same table but the first and second column GUID must be renamed. I can rename the second column GUID quite easily but how would I rename the first Column's GUID? This is the sql query that renames the second column and copies into the same table: string newToolGUID = System.Guid.NewGuid().ToString("B"); insert into strtrigger select @newToolGUID as stoolguid, striggergu...

How to add rows to a table
Hi all, I've just practice ASP.Net for a few days. When I drag a "<asp:Table" tag from controlbar to the webform, I cannot add rows to that table by drag, I have to add rows to table by write code of exactly each cell/row. Can I add rows to table by drag only? If I add rows to table by manually, how can I access to a specified cell? because VS does not generate a approriate variable to each cell when I add cells by manually, while cell[0][0] is a text box and sell[1][2] is a check box for example. Thank you! you should be able to add <asp:tablerow> <asp:t...

Error appears: "This row already belongs to this table." on add row to a datatable
The error message "This row already belongs to this table." appears when I attempt to add a 2nd row to a datatable.  The code is as follows: ==================================================================  Dim dtTrans As New DataTable 'Set up datatable columns dtTrans.Columns.Add(New DataColumn("EventDate", Type.GetType("System.DateTime"))) dtTrans.Columns.Add(New DataColumn("PostDate", Type.GetType("System.DateTime"))) dtTrans.Columns.Add(New DataColumn("PostCode", Type.GetType("System.String"))) dtTrans.Columns.Add(New DataColumn("PostCodeDesc", Type.GetType("System.S...

how can i add row to table of sql with vb.net code?
how can i add row to table of sql with vb.net code?  You can use System.Data.SqlClient classes :  Using con As New SqlConnection(" your connection string goes here ") Dim com As New SqlCommand("Insert into Person (id,name) values(@id,@name) ", con) com.Parameters.AddWithValue("@id", 1) com.Parameters.AddWithValue("@name", "Nomi1") com.Connection.Open...

How to add new rows in the form of rows
Hi, I can able to insert,delete and update record in gridview but cannot able to insert any new rows in the gird. In windows application we can insert new records(using DataGridView) into the database but not in web page. How to insert the records in gridview like control. Please tell me how to insert records in database in the form of rows. I mean i want to enter 20 records at one time.   Thanks.   Regards ArshadPlease Mark as Answer if the post is helpful to you. hi, Have you set the property AllowUserToAddRows=True; for the datagridview?????  If you are us...

Web resources about - Add row to table with table.row.add() - asp.net.web-forms

Table of United States Core Based Statistical Areas - Wikipedia, the free encyclopedia
for the United States of America . The OMB defines a Core Based Statistical Area as one or more adjacent counties or county equivalents that ...

Another problem lands on Malcolm Turnbull's tax reform table
If the Prime Minister wants an honest debate about tax reform, he now has an even more cogent case for everything being on the table.

Women missing at the business-lunch table
Long lunches. It's the way to do business, when you're a man.

Pinball Labs wants to bring classic gaming tables to VR
... by letting users have an unprecedented level of immersion with VR as well as giving them the tools to design and share their own virtual tables ...

"I've got to be honest with you. I've got to lay it out on the table: I also went to the bathroom."
"I know. I have to admit it. I guess other men are allowed to go to the bathroom, but women, what can we say?" Said Bernie Sanders , reacting ...

Microsoft has raised the price of its giant 84-inch touchscreen table to $21,999
Microsoft is hiking the price of both its upcoming Surface Hub models and is pushing the shipping date back, ZDNet reports . The 84-inch model ...

Sarah Palin turns the tables on Tina Fey
The former vice presidential candidate played one of Fey's fictional characters in a spoof

Take money off the table: Yamada:
The S&P 500 just saw its first two-day winning streak in over a month, but Louise Yamada warns of disturbing price action.

Applebee’s Server Returns $32,000 In Cash Family Accidentally Left On The Table
If you work in a restaurant, finding a large amount of cash on the table might be one of those moments where you think you’ve just lucked out ...

Whiny Rand Paul Vows Not To Take His Seat At 'The Kiddie Table'
If he can't play with the big kids, Rand says he'll take his bat & ball and go home. Source: Politico Rand Paul will not accept being relegated ...

Resources last updated: 12/30/2015 9:18:51 AM