ASP.net: Menambahkan Custom TableRow Secara Dinamis

Di projek yang sedang saya kerjakan, ada form isian yang dinamis. Secara default, form isiannya hanya tersedia 1 baris, tapi user bisa menambah baris baru, berapapun banyaknya. Yang menjadi masalah, banyak control yang tersedia di form isian tersebut. Jadi selain membuat tablerow baru, juga harus membuat beberapa control seperti textbox, dropdownlist dan checkbox secara dinamis. Dan bagaimana mendapatkan value dari setiap control.

Awalnya hanya tersedia satu baris

Ketika user klik tombol 'tambah', baris baru terbentuk

Jadi, bagaimana membuatnya? Pertama, buat file aspx, seperti berikut. (Klik kode dibawah ini untuk melihat kode selengkapnya)

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_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>Add New Table Row</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Table ID="Table1" runat="server" CellPadding="3" CellSpacing="0" BorderWidth="2"
            Width="100%" Font-Names="Verdana" Font-Size="12px" GridLines="Both">
            <asp:TableHeaderRow ID="headerrow" runat="server">
                <asp:TableCell ID="hc1" runat="server" HorizontalAlign="Center" BorderWidth="2"><b>No.</b></asp:TableCell>
                <asp:TableCell ID="hc2" runat="server" ColumnSpan="3" HorizontalAlign="Center" BorderWidth="2"><b>Nama barang</b> <br /> <i>Item code / Name</i></asp:TableCell>
                <asp:TableCell ID="hc5" runat="server" HorizontalAlign="Center" BorderWidth="2"><b>Satuan Unit</b></asp:TableCell>
                <asp:TableCell ID="hc6" runat="server" HorizontalAlign="Center" BorderWidth="2"><b>Jumlah Total</b></asp:TableCell>
                <asp:TableCell ID="hc7" runat="server" HorizontalAlign="Center" BorderWidth="2"><b>Deskripsi Barang</b><br /><i>(Kualitas Pengepakan)</i></asp:TableCell>
                <asp:TableCell ID="hc8" runat="server" HorizontalAlign="Center" BorderWidth="2"><b>Tujuan</b><br /><i>Destination</i></asp:TableCell>
                <asp:TableCell ID="hc9" runat="server" HorizontalAlign="Center" BorderWidth="2">&nbsp;</asp:TableCell>
            </asp:TableHeaderRow>
            <asp:TableRow ID="TableRow1" runat="server">
                <asp:TableCell ID="tablecell1" runat="server" HorizontalAlign="Center" BorderWidth="2">1.</asp:TableCell>
                <asp:TableCell ID="tablecell2" runat="server" HorizontalAlign="Center" BorderWidth="2">
                    <asp:DropDownList ID="ddlGroup" runat="server" Width="100">
                        <asp:ListItem Text="satu" Value="1" />
                        <asp:ListItem Text="dua" Value="2" />
                        <asp:ListItem Text="tiga" Value="3" />
                    </asp:DropDownList>
                </asp:TableCell>
                <asp:TableCell ID="tablecell3" runat="server" HorizontalAlign="Center" BorderWidth="2">
                    <asp:DropDownList ID="ddlJenis" runat="server" Width="100">
                    </asp:DropDownList>
                </asp:TableCell>
                <asp:TableCell ID="tablecell4" runat="server" HorizontalAlign="Center" BorderWidth="2">
                    <asp:DropDownList ID="ddlItem" runat="server" Width="100">
                    </asp:DropDownList>
                </asp:TableCell>
                <asp:TableCell ID="tablecell5" runat="server" HorizontalAlign="Center" BorderWidth="2">
                    <asp:TextBox ID="tbUnit" runat="server" Width="40"></asp:TextBox>
                </asp:TableCell>
                <asp:TableCell ID="tablecell6" runat="server" HorizontalAlign="Center" BorderWidth="2">
                    <asp:TextBox ID="tbTotal" runat="server" Width="40"></asp:TextBox>
                </asp:TableCell>
                <asp:TableCell ID="tablecell7" runat="server" HorizontalAlign="Center" BorderWidth="2">
                    <asp:TextBox ID="tbDeskripsi" runat="server" Width="170"></asp:TextBox>
                </asp:TableCell>
                <asp:TableCell ID="tablecell8" runat="server" HorizontalAlign="Center" BorderWidth="2">
                    <asp:TextBox ID="tbTujuan" runat="server" Width="110"></asp:TextBox>
                </asp:TableCell>
                <asp:TableCell ID="tablecell9" runat="server" HorizontalAlign="Center" BorderWidth="2">
                    <asp:CheckBox ID="cb" runat="server" />
                </asp:TableCell>
            </asp:TableRow>
        </asp:Table><br />
        <asp:Button ID="Button1" runat="server" Text="Nambah" />
        <asp:Button ID="Button2" runat="server" Text="Get Value" />
    </div>
    </form>
</body>
</html>

Kedua, buat class dengan nama “NewTableRow.vb”. Klik tombol di bawah ini, untuk melihat kode selengkapnya

Imports Microsoft.VisualBasic

Public Class NewTableRow
    Private _ddlGroupID As Integer = -1
    Private _ddlJenisID As Integer = -1
    Private _ddlItemID As Integer = -1
    Private _tbSatuanID As Integer = -1
    Private _tbJumlahID As Integer = -1
    Private _tbTujuanID As Integer = -1
    Private _tbDeskripsiID As Integer = -1
    Private _checkboxID As Integer = -1

    Private _JmlRow As Integer
    Private _targetTable As System.Web.UI.WebControls.Table
    Private _tr As TableRow

    Public Sub New(ByVal targettable As System.Web.UI.WebControls.Table, _
                   ByVal jumlahRow As Integer)
        _targetTable = targettable
        _JmlRow = jumlahRow
    End Sub

    Public Property TargetTable() As System.Web.UI.WebControls.Table
        Get
            Return _targetTable
        End Get
        Set(ByVal value As System.Web.UI.WebControls.Table)
            _targetTable = value
        End Set
    End Property

    Public Property JumlahRow() As Integer
        Get
            Return _JmlRow
        End Get
        Set(ByVal value As Integer)
            _JmlRow = value
        End Set
    End Property

    Private Function DdlID(ByVal ddlname As String) As String
        Dim NewDdlID As String = String.Empty

        Select Case ddlname.ToLower()
            Case "group"
                If Me._ddlGroupID = -1 Then
                    Me._ddlGroupID = TargetTable.Rows.Count
                End If

                NewDdlID = String.Format("ddlGroup{0}", (Me._ddlGroupID + 1).ToString())
                Me._ddlGroupID += 1
            Case "jenis"
                If Me._ddlJenisID = -1 Then
                    Me._ddlJenisID = TargetTable.Rows.Count
                End If

                NewDdlID = String.Format("ddlJenis{0}", (Me._ddlJenisID + 1).ToString())
                Me._ddlJenisID += 1
            Case "item"
                If Me._ddlItemID = -1 Then
                    Me._ddlItemID = TargetTable.Rows.Count
                End If

                NewDdlID = String.Format("ddlItem{0}", (Me._ddlItemID + 1).ToString())
                Me._ddlItemID += 1
        End Select

        Return NewDdlID
    End Function

    Private Function TextBoxID(ByVal tbName As String) As String
        Dim NewTextboxID As String = String.Empty

        Select Case tbName.ToLower()
            Case "satuan"
                If Me._tbSatuanID = -1 Then
                    Me._tbSatuanID = TargetTable.Rows.Count
                End If
                NewTextboxID = String.Format("tbUnit{0}", (Me._tbSatuanID + 1).ToString())
                Me._tbSatuanID += 1
            Case "jumlah"
                If Me._tbJumlahID = -1 Then
                    Me._tbJumlahID = TargetTable.Rows.Count
                End If
                NewTextboxID = String.Format("tbTotal{0}", (Me._tbJumlahID + 1).ToString())
                Me._tbJumlahID += 1
            Case "deskripsi"
                If Me._tbDeskripsiID = -1 Then
                    Me._tbDeskripsiID = TargetTable.Rows.Count
                End If
                NewTextboxID = String.Format("tbDeskripsi{0}", (Me._tbDeskripsiID + 1).ToString())
                Me._tbDeskripsiID += 1
            Case "tujuan"
                If Me._tbTujuanID = -1 Then
                    Me._tbTujuanID = TargetTable.Rows.Count
                End If
                NewTextboxID = String.Format("tbTujuan{0}", (Me._tbTujuanID + 1).ToString())
                Me._tbTujuanID += 1
        End Select
        Return NewTextboxID
    End Function

    Private Function CheckBoxID() As String
        If Me._checkboxID = -1 Then
            Me._checkboxID = TargetTable.Rows.Count
        End If
        Dim newCbID As String = String.Format("cb{0}", (Me._checkboxID + 1).ToString())
        Me._checkboxID += 1
        Return newCbID
    End Function

    Public Function AddAdditonalRow(ByVal incrementcounter As Boolean) As TableRow

        Dim tr As New TableRow
        Dim cell1, cell2, cell3, cell4, cell5, cell6, cell7, cell8, cell9 As New TableCell

        cell1.BorderWidth = 2
        cell1.HorizontalAlign = HorizontalAlign.Center
        tr.Cells.Add(cell1)
        cell2.HorizontalAlign = HorizontalAlign.Center
        tr.Cells.Add(cell2)
        cell3.HorizontalAlign = HorizontalAlign.Center
        tr.Cells.Add(cell3)
        cell4.HorizontalAlign = HorizontalAlign.Center
        tr.Cells.Add(cell4)
        cell5.HorizontalAlign = HorizontalAlign.Center
        tr.Cells.Add(cell5)
        cell6.HorizontalAlign = HorizontalAlign.Center
        tr.Cells.Add(cell6)
        cell7.HorizontalAlign = HorizontalAlign.Center
        tr.Cells.Add(cell7)
        cell8.HorizontalAlign = HorizontalAlign.Center
        tr.Cells.Add(cell8)
        cell9.HorizontalAlign = HorizontalAlign.Center
        tr.Cells.Add(cell9)

        Dim ddl1 As New DropDownList
        ddl1.ID = DdlID("group")
        ddl1.Items.Add("satu")
        ddl1.Items.Add("dua")
        ddl1.Items.Add("tiga")
        ddl1.Items(0).Value = 1
        ddl1.Items(1).Value = 2
        ddl1.Items(2).Value = 3
        ddl1.Width = 100

        cell2.Controls.Add(ddl1)

        Dim ddl2 As New DropDownList
        ddl2.ID = DdlID("jenis")
        ddl2.Width = 100
        cell3.Controls.Add(ddl2)

        Dim ddl3 As New DropDownList
        ddl3.ID = DdlID("Item")
        ddl3.Width = 100
        cell4.Controls.Add(ddl3)

        Dim tbSatuan As New TextBox
        tbSatuan.ID = TextBoxID("satuan")
        tbSatuan.Width = 40
        cell5.Controls.Add(tbSatuan)

        Dim tbJumlah As New TextBox
        tbJumlah.ID = TextBoxID("jumlah")
        tbJumlah.Width = 40
        cell6.Controls.Add(tbJumlah)

        Dim tbDeskripsi As New TextBox
        tbDeskripsi.ID = TextBoxID("deskripsi")
        tbDeskripsi.Width = 170
        cell7.Controls.Add(tbDeskripsi)

        Dim tbTujuan As New TextBox
        tbTujuan.ID = TextBoxID("tujuan")
        tbTujuan.Width = 110
        cell8.Controls.Add(tbTujuan)

        Dim cb As New CheckBox
        cb.ID = CheckBoxID
        cell9.Controls.Add(cb)

        TargetTable.Rows.Add(tr)

        If incrementcounter Then
            JumlahRow += 1
        End If

        Return tr
    End Function

    Public Sub GenerateNomorBaris(ByRef tr As TableRow)
        'buat nomor baris di kolom pertama
        tr.Cells(0).Text = String.Format("{0}.", TargetTable.Rows.GetRowIndex(tr).ToString())
    End Sub
End Class

Buka file codebehind, tambahkan kode berikut

Partial Class _Default
    Inherits System.Web.UI.Page

    Private _jmlRow As Integer = 0
    Private targetTable As Table = Nothing

    Protected Sub Page_PreInit(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreInit
        'inisialisasi awal
        targetTable = Me.Table1
        Integer.TryParse(Request.Form("JMLROW"), _jmlRow)

        Dim tableForm As New NewTableRow(targetTable, _jmlRow)
        If _jmlRow > 0 Then
            Dim i As Integer = 0
            While i < _jmlRow
                'tabel yang ada dibentuk ulang
                'jadi nilainya false, agar gak terbentuk row baru
                tableForm.AddAdditonalRow(False)
                i += 1
            End While
        End If
    End Sub

    Protected Sub Page_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRender
        'simpan informasi jumlah row dari tabel di hidden field.
        'Jika menggunakan AJAX, informasi jumlah row sebaiknya disimpan di dalam session
        ClientScript.RegisterHiddenField("JMLROW", _jmlRow.ToString())
    End Sub

    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
        'row baru dibuat
        Dim tableform As New NewTableRow(targetTable, _jmlRow)
        Dim tr As TableRow = tableform.AddAdditonalRow(True)
        tableform.GenerateNomorBaris(tr)
        _jmlRow = tableform.JumlahRow
    End Sub
End Class

Di sub page_preinit, tabel akan dibuat seperti semula tanpa menambahkan baris baru. Penambahan tablerow baru dilakukan di method button_click. Di sub page_prerender, informasi jumlah baris dari tabel, disimpan dalam hiddenfield. Jika menggunakan AJAX, informasi ini sebaiknya disimpan di session.

Mendapatkan value dari control

Untuk mendapatkan value dari masing-masing control, gunakan looping pada tiap-tiap tablerow. Misal jika ingin membaca value dari textbox di cell 5

For i As Integer = 1 To targetTable.Rows.Count - 1
Dim tb As TextBox = CType(DirectCast(targetTable.Rows(i).Cells(5), System.Web.UI.WebControls.TableCell).Controls(0), TextBox)
If Not tb Is Nothing Then
   Response.Write(String.Format("value:{0};<br/>", tb.Text.ToString()))
End If
Next

Semoga bisa membantu. Salam

Download Sample

About Yuniar

Penulis sekarang lebih banyak bekerja menggunakan teknologi Microsoft .NET secara umum dan TIDAK lagi menggunakan aplikasi MapXtreme.net dari MapInfo. Karena itu mohon maaf, jika pertanyaan-pertanyaan mengenai MapXtreme sudah tidak bisa saya jawab lagi.

Posted on 18 Februari 2010, in ASP.net and tagged , , , , , . Bookmark the permalink. 4 Komentar.

  1. Mas tolong klo nilai dari ntabel disimpan di databse sql serevr gmn sintaknya?

    Mohon bantuannya…
    Terima kasih

  2. matab…
    thx gan..
    sangat membantu nih artikelnyašŸ˜‰

  1. Ping-balik: Asp.net: Dinamic Gridview | AK:new BlogNote[Ku]

Tinggalkan Balasan

Isikan data di bawah atau klik salah satu ikon untuk log in:

Logo WordPress.com

You are commenting using your WordPress.com account. Logout / Ubah )

Gambar Twitter

You are commenting using your Twitter account. Logout / Ubah )

Foto Facebook

You are commenting using your Facebook account. Logout / Ubah )

Foto Google+

You are commenting using your Google+ account. Logout / Ubah )

Connecting to %s

%d blogger menyukai ini: