[c#] How to dynamically add rows to a table in ASP.NET?

So today I started learning ASP.NET. Unfortunately I haven't found any good tutorials online, and I can't afford to buy books at the moment, so I've had to create a ASP.NET web application in Visual Studio 2010 and just play around with the default project setup.

So far here's what I have in my Default.aspx:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Project Management</title>
</head>
<body>
    <div style="padding-bottom:10px;"> Project Management System</div>
    <div> <table style="width:100%;">
            <tr>
                <td>Name</td>
                <td>Task</td>
                <td>Hours</td>
            </tr>
    </table></div>
</body>
</html>

I created a simple table with the header row already in there. Through a C# script, I want to be able to dynamically add rows to this HTML table. Is this the right way of thinking in ASP.NET? If so, how can I do this? I'm sure I'll need an "Add" button, which adds a new row to the table, with editable fields, and a "submit" button which adds some stuff to a database.

Basically just a rundown of how this is done would be ever so helpful. Also if anyone knows any good tutorials or websites that can help me out with things like this, please let me know.

Thanks in advance.

This question is related to c# asp.net visual-studio-2010

The answer is


You can use the asp:Table in your web form and build it via code:

http://msdn.microsoft.com/en-us/library/7bewx260.aspx

Also, check out asp.net for tutorials and such.


ASP.NET WebForms doesn't work this way. What you have above is just normal HTML, so ASP.NET isn't going to give you any facility to add/remove items. What you'll want to do is use a Repeater control, or possibly a GridView. These controls will be available in the code-behind. For example, the Repeater would expose an "Items" property upon which you can add new items (rows). In the code-front (the .aspx file) you'd provide an ItemTemplate that stubs out what the body rows would look like. There are plenty of tutorials on the web for repeaters, so I suggest you google that to obtain further information.


<html>
<head>
  <title>Row Click</title>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script>
        function test(){
            alert('test');
        }
  $(document).ready(function(){
        var row='<tr onclick="test()"><td >Value 4</td><td>Value 5</td><td>Value 6</td></tr>';
        $("#myTable").append(row);
});
  </script>
</head>
<table id="myTable" >
<th>Column 1</th><th>Column 2</th><th>Column 3</th>
<tr onclick="test()">
    <td >Value 1</td>
    <td>Value 2</td>
    <td>Value 3</td>
</tr>
</table>
</html>

Dynamically Created for a Row in a Table

See below the Link

http://msdn.microsoft.com/en-us/library/7bewx260(v=vs.100).aspx


in addition to what Kirk said I want to tell you that just "playing around" won't help you to learn asp.net, and there is a lot of free and very good tutorials .
take a look on the asp.net official site tutorials and on 4GuysFromRolla site


public partial class result : System.Web.UI.Page
{
    static DataTable table1 = new DataTable("Shashank");
    static DataSet set = new DataSet("office");


    protected void Page_Load(object sender, EventArgs e)
    {
        lblEmployeeNumber.Text = HttpContext.Current.Request.Form["txtEmployeeNumber"];
        lblFirstName.Text = Request.Form["txtFirstName"];
        lblLastName.Text = Request.Form["txtLastName"];
        lblTitle.Text = Request.Form["txtTitle"];

        Int32 Rcount = Convert.ToInt32(table1.Rows.Count);

        if (Rcount == 0)
        {

            table1.Columns.Add("ID");
            table1.Columns.Add("FName");
            table1.Columns.Add("LName");
            table1.Columns.Add("Title");
            table1.Rows.Add(lblEmployeeNumber.Text, lblFirstName.Text, lblLastName.Text, lblTitle.Text);
            set.Tables.Add(table1);
        }
        else
        {
            if (lblEmployeeNumber.Text != "")
            {
                DataRow dr = table1.NewRow();
                dr["ID"] = lblEmployeeNumber.Text;
                dr["FName"] = lblFirstName.Text;
                dr["LName"] = lblLastName.Text;
                dr["Title"] = lblTitle.Text;
                table1.Rows.Add(dr);
            }
        }

        gvrEmp.DataSource = set;
        gvrEmp.DataBind();

    }
}

You need to get familiar with the idea of "Server side" vs. "Client side" code. It's been a long time since I had to start, but you may want to start with some of the video tutorials at http://www.asp.net.

Two things to note: if you're using VS2010 you actually have two different frameworks to chose from for ASP.NET: WebForms and ASP.NET MVC2. WebForms is the old legacy way, MVC2 is being positioned by MS as an alternative not a replacement for WebForms, but we'll see how the community handles it over the next couple of years. Anyway, be sure to pay attention to which one a given tutorial is talking about.


Link for adding through JS https://www.youtube.com/watch?v=idyyQ23joy0

Please see the below link as well. This would help you add the rows dynamically on the fly: https://www.lynda.com/C-tutorials/Adding-data-HTML-tables-runtime/161815/366843-4.html


You need to use JavaScript in your HTML and make sure you are using forms so that. You may finally serialize the data using Ajax method to push the data from HTML into database


Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to asp.net

RegisterStartupScript from code behind not working when Update Panel is used You must add a reference to assembly 'netstandard, Version=2.0.0.0 No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization How to use log4net in Asp.net core 2.0 Visual Studio 2017 error: Unable to start program, An operation is not legal in the current state How to create roles in ASP.NET Core and assign them to users? How to handle Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause() ASP.NET Core Web API Authentication Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0 WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

Examples related to visual-studio-2010

variable is not declared it may be inaccessible due to its protection level SSIS Excel Connection Manager failed to Connect to the Source This project references NuGet package(s) that are missing on this computer Gridview get Checkbox.Checked value error LNK2038: mismatch detected for '_MSC_VER': value '1600' doesn't match value '1700' in CppFile1.obj What is the difference between Visual Studio Express 2013 for Windows and Visual Studio Express 2013 for Windows Desktop? Attach (open) mdf file database with SQL Server Management Studio What is and how to fix System.TypeInitializationException error? Could not load file or assembly "Oracle.DataAccess" or one of its dependencies IIS error, Unable to start debugging on the webserver