Insert dynamically generated TextBox value in database using C# and VB.Net in ASP.Net

Last Reply 22 days ago By pandeyism

Posted 22 days ago

I want to insert data in data base from dynamically generated textboxes. I am using below code but it is not working properly and giving me errors.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="test_table_dynamic.aspx.cs" Inherits="Test_captcha.test_table_dynamic" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <link href="Content/bootstrap.css" rel="stylesheet" />
    <script src="Scripts/jquery-3.0.0.js"></script>
    <script src="Scripts/bootstrap.js"></script>
    <script type="text/javascript">
        function addRow(tableID) {
            var table = document.getElementById(tableID);
            var rowCount = table.rows.length;
            var row = table.insertRow(rowCount);
            var colCount = table.rows[0].cells.length;
            for (var i = 0; i < colCount; i++) {
                var newcell = row.insertCell(i);
                newcell.innerHTML = table.rows[0].cells[i].innerHTML;
                //alert(newcell.childNodes);
                switch (newcell.childNodes[0].type) {
                    case "text":
                        newcell.childNodes[0].value = "";
                        break;
                    case "checkbox":
                        newcell.childNodes[0].checked = false;
                        break;
                    case "select-one":
                        newcell.childNodes[0].selectedIndex = 0;
                        break;
                }
            }
        }

        function deleteRow(tableID) {
            try {
                var table = document.getElementById(tableID);
                var rowCount = table.rows.length;

                for (var i = 0; i < rowCount; i++) {
                    var row = table.rows[i];
                    var chkbox = row.cells[0].childNodes[1];
                    if (chkbox != null && chkbox.checked == true) {
                        if (rowCount <= 1) {
                            alert("Cannot delete all the rows.");
                            break;
                        }
                        table.deleteRow(i);
                        rowCount--;
                        i--;
                    }
                }
            } catch (e) {
                alert(e);
            }
        }
    </script>
</head>

 

        protected void sprink_submit_Click(object sender, EventArgs e)
        {
            SqlCommand cmd = new SqlCommand("insert into company_sprinkler_data_test(company_email,nozzle_lph,noozle_price,lateral_mm,lateral_price,main_mm,main_price,Sp_mpump_hp,Sp_mpump_price)values(@company_email,@nozzle_lph,@nozzle_price,@lateral_mm,@lateral_price,@main_mm,@main_price,@Sp_mpump_hp,@Sp_mpump_price)");
            con.Open();
            cmd.Connection = con;
            cmd.CommandType = CommandType.Text;

            cmd.Parameters.AddWithValue("@company_email", c_email.Text.Trim().ToString());
            cmd.Parameters.AddWithValue("@nozzle_lph", nozzle_lph.Text.Trim().ToString());
            cmd.Parameters.AddWithValue("@nozzle_price", nozzle_price.Text.Trim().ToString());
            cmd.Parameters.AddWithValue("@lateral_mm", txt_lat_mm.Text.Trim().ToString());
            cmd.Parameters.AddWithValue("@lateral_price", txt_lat_price.Text.Trim().ToString());
            cmd.Parameters.AddWithValue("@submain_mm", txt_smain_mm.Text.Trim().ToString());
            cmd.Parameters.AddWithValue("@submain_price", txt_smain_price.Text.Trim().ToString());
            cmd.Parameters.AddWithValue("@main_mm", txt_main_mm.Text.Trim().ToString());
            cmd.Parameters.AddWithValue("@main_price", txt_main_price.Text.Trim().ToString());
            cmd.Parameters.AddWithValue("@Sp_mpump_hp", txt_mpum_hp.Text.Trim().ToString());
            cmd.Parameters.AddWithValue("@Sp_mpump_price", txt_mpump_price.Text.Trim().ToString());

            int row;
            try
            {
                row = cmd.ExecuteNonQuery();
                if (row > 0)
                {
                    ScriptManager.RegisterStartupScript(this, GetType(), "alert", "alert('Price added Sucessful');window.location='MIS_login.aspx';", true);
                }
                else
                {
                    ScriptManager.RegisterStartupScript(this, GetType(), "alert", "alert('Add Prices again');", true);
                }
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                if (con.State == ConnectionState.Open)
                    con.Close();

            }
        }

 

Posted 22 days ago Modified on 21 days ago

Hi nid@patel,

Refer below sample.

HTML

<script type="text/javascript">
    function addRow(tableID) {
        var table = document.getElementById(tableID);
        var rowCount = table.rows.length;
        var row = table.insertRow(rowCount);
        var colCount = table.rows[0].cells.length;
        for (var i = 0; i < colCount; i++) {
            var newcell = row.insertCell(i);
            newcell.innerHTML = table.rows[0].cells[i].innerHTML;
            switch (newcell.childNodes[0].type) {
                case "text":
                    newcell.childNodes[0].value = "";
                    break;
                case "checkbox":
                    newcell.childNodes[0].checked = false;
                    break;
                case "select-one":
                    newcell.childNodes[0].selectedIndex = 0;
                    break;
            }
        }
    }

    function deleteRow(tableID) {
        try {
            var table = document.getElementById(tableID);
            var rowCount = table.rows.length;
            for (var i = 0; i < rowCount; i++) {
                var row = table.rows[i];
                var chkbox = row.cells[0].childNodes[1];
                if (chkbox != null && chkbox.checked == true) {
                    if (rowCount <= 1) {
                        alert("Cannot delete all the rows.");
                        break;
                    }
                    table.deleteRow(i);
                    rowCount--;
                    i--;
                }

            }
        } catch (e) {
            alert(e);
        }
    }        
</script>
<div class="container">
    <ul class="responsive-table">
        <li class="table-row">
            <div class="col col-1" data-label="Job Id">
                Nozzle</div>
            <div class="col col-2">
                <table id="dataTable1" class="table-bordered table-hover table-striped table" runat="server">
                    <tr>
                        <td>
                            <input type="checkbox" name="chk" />
                        </td>
                        <td>
                            <asp:TextBox ID="nozzle_lph" runat="server" type="text" placeholder="LPH"></asp:TextBox>
                        </td>
                        <td>
                            <asp:TextBox ID="nozzle_price" runat="server" type="text" placeholder="RS./unit"></asp:TextBox>
                        </td>
                    </tr>
                </table>
            </div>
            <div class="col col-3">
            </div>
            <div class="col col-4">
                <input type="button" class="btn btn-danger active" value="Add Row" onclick="addRow('dataTable1')" /><hr />
                <input type="button" class="btn btn-info active" value="Delete Row" onclick="deleteRow('dataTable1')" />
                <asp:Button ID="sprink_submit" runat="server" CssClass="btn btn-danger btn-group-lg active"
                    Text="Submit" OnClick="sprink_submit_Click" />
            </div>
        </li>
    </ul>
</div>
<br />
<asp:GridView runat="server" ID="gvData" AutoGenerateColumns="false">
    <Columns>
        <asp:BoundField DataField="nozzle_lph" HeaderText="nozzle_lph" />
        <asp:BoundField DataField="nozzle_price" HeaderText="nozzle_price" />
    </Columns>
</asp:GridView>

Namespaces

C#

using System.Data;
using System.Data.SqlClient;
using System.Configuration;

VB.Net

Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration

Code

C#

protected void sprink_submit_Click(object sender, EventArgs e)
{
    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    SqlConnection con = new SqlConnection(constr);
    SqlCommand cmd = new SqlCommand("INSERT INTO tblCompanyData(nozzle_lph,nozzle_price) VALUES(@nozzle_lph,@nozzle_price)", con);
    string[] textboxValues1 = Request.Form.GetValues("nozzle_lph");
    string[] textboxValues2 = Request.Form.GetValues("nozzle_price");
    for (int i = 0; i < textboxValues1.Length; i++)
    {
        cmd = new SqlCommand("INSERT INTO tblCompanyData(nozzle_lph,nozzle_price) VALUES(@nozzle_lph,@nozzle_price)", con);
        cmd.Parameters.AddWithValue("@nozzle_lph", textboxValues1[i]);
        cmd.Parameters.AddWithValue("@nozzle_price", textboxValues2[i]);
        con.Open();
        cmd.ExecuteNonQuery();
        con.Close();
    }
    cmd = new SqlCommand("SELECT nozzle_lph,nozzle_price FROM tblCompanyData", con);
    SqlDataAdapter da = new SqlDataAdapter(cmd);
    DataTable dt = new DataTable();
    da.Fill(dt);
    gvData.DataSource = dt;
    gvData.DataBind();
}

 

Protected Sub sprink_submit_Click(ByVal sender As Object, ByVal e As EventArgs)
    Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
    Dim con As SqlConnection = New SqlConnection(constr)
    Dim cmd As SqlCommand = New SqlCommand("INSERT INTO tblCompanyData(nozzle_lph,nozzle_price) VALUES(@nozzle_lph,@nozzle_price)", con)
    Dim textboxValues1 As String() = Request.Form.GetValues("nozzle_lph")
    Dim textboxValues2 As String() = Request.Form.GetValues("nozzle_price")
    For i As Integer = 0 To textboxValues1.Length - 1
        cmd = New SqlCommand("INSERT INTO tblCompanyData(nozzle_lph,nozzle_price) VALUES(@nozzle_lph,@nozzle_price)", con)
        cmd.Parameters.AddWithValue("@nozzle_lph", textboxValues1(i))
        cmd.Parameters.AddWithValue("@nozzle_price", textboxValues2(i))
        con.Open()
        cmd.ExecuteNonQuery()
        con.Close()
    Next
    cmd = New SqlCommand("SELECT nozzle_lph,nozzle_price FROM tblCompanyData", con)
    Dim da As SqlDataAdapter = New SqlDataAdapter(cmd)
    Dim dt As DataTable = New DataTable()
    da.Fill(dt)
    gvData.DataSource = dt
    gvData.DataBind()
End Sub

Screenshot