Insert record in Nested Repeater on Button Click using C# and VB.Net in ASP.Net

RichardSa
 
on Sep 14, 2021 12:47 AM
Sample_958977.zip
962 Views

I want to learn how to add record to a nested Repeater inside DataList. I was recently shown a method on how to update an existing record in the nested Repeater inside DataList control.

I tried to use that method on DataList because it is the record that will show in the Repeater. In my code I have "Add Option" button that is attached to DataList control.

So that when user click on the "Add Option" button, they will add record that will display in the nested repeater.

The Problem I have right now is that when I viewed it in the browser, other records belonging to other Admins also display because I added the hiddenfield("Id") to the DataList control and also selected it in this line of code in C#:

 DataTable dt = GetData("SELECT DISTINCT Id, BallotQuestion FROM Questions WHERE AdminName = '" + Adminlbl.Text + "' AND ElectionName = '" + electlbl.Text + "'");

HTML

<div class="col" style="width: 100%; margin: 0 auto; padding: 10px;">
    <asp:Label ID="Adminlbl" runat="server" Text="Richard" />
    <asp:Label ID="electlbl" runat="server" Text="2021 Youth Elections" />
    <asp:DataList runat="server" ID="dlquestion" CssClass="row" CellPadding="4" OnItemDataBound="dlquestion_ItemDataBound" Width="100%">
        <ItemTemplate>
            <div class="card p-3 mb5 bg-white rounded" style="border: 1px solid #d1d5d4; margin: 0 auto; padding: 10px; width: 100%; border-radius: 10px;">
                 <asp:HiddenField ID="hfElectionID" runat="server" Value='<%# Eval("Id") %>' />
                <asp:Label ID="lblQuestion" Text='<%# Eval("BallotQuestion") %>' runat="server" Font-Bold="true" Font-Names="Varela Round" Font-Size="16pt" />
                <asp:Repeater ID="rptOptions" runat="server">
                    <HeaderTemplate></HeaderTemplate>
                    <ItemTemplate>
                        <div runat="server" id="innerTable">
                            <div class="" id="middleTable">
                                <img alt="" src="images/home/lock.png" height="80" />
                                <br />
                                <div>
                                    <asp:Label ID="Label1" runat="server" Text="NAME: " Font-Bold="true" Font-Size="13pt"></asp:Label>
                                    <asp:Label ID="candlbl" runat="server" Text='<%# Eval("CandidateName") %>' />
                                </div>
                                <br />
                                <div>
                                    <asp:Label ID="Label2" runat="server" Text="BIO: " Font-Bold="true" Font-Size="13pt"></asp:Label>
                                    <asp:Label ID="biolabel" Text='<%# Eval("Shortbio") %>' runat="server" />
                                </div>
                                <br />
                                <br />
                            </div>
                        </div>
                    </ItemTemplate>
                </asp:Repeater>
                <asp:Button ID="Button1" runat="server" Text="Add Option" CssClass="btn btn-primary" OnClick="OnEdit" />
            </div>
        </ItemTemplate>
    </asp:DataList>
    <div id="dialog" style="display: none;">
        <asp:HiddenField ID="hfID" runat="server" />
        Name: <asp:TextBox runat="server" ID="txtname"></asp:TextBox>
        <asp:FileUpload ID="fuUpload" runat="server" />
        <asp:Button Text="Update" runat="server" OnClick="OnUpdate" />
    </div>
</div>

 

protected void Page_Load(object sender, EventArgs e)
{
    DataTable dt = GetData("SELECT DISTINCT Id, BallotQuestion FROM Questions WHERE AdminName = '" + Adminlbl.Text + "' AND ElectionName = '" + electlbl.Text + "'");
    dlquestion.RepeatColumns = dt.Rows.Count;
    dlquestion.DataSource = dt;
    dlquestion.DataBind();
    dlquestion.RepeatColumns = 1;
    dlquestion.RepeatDirection = RepeatDirection.Vertical;
}
 
protected void dlquestion_ItemDataBound(object sender, DataListItemEventArgs e)
{
    if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
    {
        string BallotQuestion = (e.Item.FindControl("lblQuestion") as Label).Text;
        Repeater rptOptions = e.Item.FindControl("rptOptions") as Repeater;
        rptOptions.DataSource = GetData("SELECT CandidateName,Shortbio FROM Questions WHERE BallotQuestion = '" + BallotQuestion + "'");
        rptOptions.DataBind();
    }
}
 
private DataTable GetData(string query)
{
    SqlCommand cmd = new SqlCommand(query);
    using (SqlConnection con = new SqlConnection("Data Source = (LocalDB)\\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\\BallotDB.mdf;Integrated Security = True;"))
    {
        using (SqlDataAdapter sda = new SqlDataAdapter())
        {
            cmd.Connection = con;
            sda.SelectCommand = cmd;
            using (DataTable dt = new DataTable())
            {
                sda.Fill(dt);
                return dt;
            }
        }
    }
}
 
protected void OnEdit(object sender, EventArgs e)
{
    DataListItem item = (sender as Button).NamingContainer as DataListItem;
    hfID.Value = (item.FindControl("hfElectionID") as HiddenField).Value;
    ClientScript.RegisterStartupScript(this.GetType(), "Popup", "ShowPopup();", true);
}
 
protected void OnUpdate(object sender, EventArgs e)
{
    int id = Convert.ToInt32(hfID.Value);
    string name = txtname.Text;
    //Code for inserting name & image based on the DataList control Id.
}

 

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Sep 16, 2021 04:41 AM

Hi RichardSa,

Refer below sample.

HTML

<asp:Label ID="Adminlbl" runat="server" Text="Richard" />
<asp:Label ID="electlbl" runat="server" Text="2021 Youth Elections" />
<asp:DataList runat="server" ID="dlquestion" CssClass="row" CellPadding="4" OnItemDataBound="dlquestion_ItemDataBound" Width="100%">
    <ItemTemplate>
        <div class="card p-3 mb5 bg-white rounded" style="border: 1px solid #d1d5d4; margin: 0 auto; padding: 10px; width: 100%; border-radius: 10px;">
            <asp:Label ID="lblQuestion" Text='<%# Eval("BallotQuestion") %>' runat="server" Font-Bold="true" Font-Names="Varela Round" Font-Size="16pt" />
            <asp:Repeater ID="rptOptions" runat="server">
                <ItemTemplate>
                    <div runat="server" id="innerTable">
                        <div class="" id="middleTable">
                            <img alt="lock" src="images/home/lock.png" height="80" />
                            <br />
                            <div>
                                <asp:HiddenField ID="hfElectionID" runat="server" Value='<%# Eval("Id") %>' />
                                <asp:Label ID="Label1" runat="server" Text="NAME: " Font-Bold="true" Font-Size="13pt"></asp:Label>
                                <asp:Label ID="candlbl" runat="server" Text='<%# Eval("CandidateName") %>' />
                            </div>
                            <br />
                            <div>
                                <asp:Label ID="Label2" runat="server" Text="BIO: " Font-Bold="true" Font-Size="13pt"></asp:Label>
                                <asp:Label ID="biolabel" Text='<%# Eval("Shortbio") %>' runat="server" />
                            </div>
                            <br />
                            <br />
                        </div>
                        <%--<div>
                            <br />
                            <asp:Button ID="Button2" runat="server" Text="Edit" CssClass="btn btn-info" Font-Size="10pt" OnClick="OnEdit" />
                            <asp:Button ID="Button3" runat="server" Text="Delete" CssClass="btn btn-danger" Font-Size="10pt" />
                        </div>
                        <hr />--%>
                    </div>
                </ItemTemplate>
            </asp:Repeater>
            <asp:Button ID="btnAddOption" runat="server" Text="Add Option" CssClass="btn btn-primary" OnClick="OnAddOption" />
        </div>
    </ItemTemplate>
</asp:DataList>
<div id="dialog" style="display: none">
    <asp:HiddenField ID="hfBallotQuestion" runat="server" />
    Candidate Name:
    <asp:TextBox runat="server" ID="txtCandidateName" />
    Shortbio:
    <asp:TextBox runat="server" ID="txtShortbio" />
    <asp:Button Text="Add" runat="server" OnClick="OnAdd"  />
</div>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.24/themes/smoothness/jquery-ui.css" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.24/jquery-ui.min.js"></script>
<script type="text/javascript">
    function ShowPopup() {
        $("#dialog").dialog({
            title: "Update record",
            buttons: {
                Close: function () {
                    $(this).dialog('close');
                }
            },
            modal: true,
            width: "480"
        });

        $("#dialog").parent().appendTo($("form:first"));
    }
</script>

Namespaces

C#

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

VB.Net

Imports System.Data
Imports System.Data.SqlClient

Code

C#

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        string query = "SELECT DISTINCT BallotQuestion FROM Election WHERE AdminName = '" + Adminlbl.Text + "' AND ElectionName = '" + electlbl.Text + "'";
        DataTable dt = GetData(query);
        dlquestion.RepeatColumns = dt.Rows.Count;
        dlquestion.DataSource = dt;
        dlquestion.DataBind();
        dlquestion.RepeatColumns = 1;
        dlquestion.RepeatDirection = RepeatDirection.Vertical;
    }
}

protected void dlquestion_ItemDataBound(object sender, DataListItemEventArgs e)
{
    if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
    {
        string BallotQuestion = (e.Item.FindControl("lblQuestion") as Label).Text;
        Repeater rptOptions = e.Item.FindControl("rptOptions") as Repeater;
        string query = "SELECT Id,CandidateName, Shortbio FROM Election WHERE BallotQuestion = '" + BallotQuestion + "' AND AdminName = '" + Adminlbl.Text + "' AND ElectionName = '" + electlbl.Text + "'";
        rptOptions.DataSource = GetData(query);
        rptOptions.DataBind();
    }
}

private DataTable GetData(string query)
{
    SqlCommand cmd = new SqlCommand(query);
    using (SqlConnection con = new SqlConnection("Server=.;DataBase=Test;UID=sa;PWD=pass@123;"))
    {
        using (SqlDataAdapter sda = new SqlDataAdapter())
        {
            cmd.Connection = con;
            sda.SelectCommand = cmd;
            using (DataTable dt = new DataTable())
            {
                sda.Fill(dt);
                return dt;
            }
        }
    }
}

protected void OnAddOption(object sender, EventArgs e)
{
    DataListItem item = (sender as Button).NamingContainer as DataListItem;
    Label ballotQuestion = item.FindControl("lblQuestion") as Label;
    hfBallotQuestion.Value = ballotQuestion.Text;
    ClientScript.RegisterStartupScript(this.GetType(), "Popup", "ShowPopup();", true);
}

protected void OnAdd(object sender, EventArgs e)
{
    string adminName = Adminlbl.Text;
    string electtionName = electlbl.Text;
    string ballotQuestion = hfBallotQuestion.Value;
    string name = txtCandidateName.Text;
    string shortbio = txtCandidateName.Text;
    using (SqlConnection con = new SqlConnection("Server=.;DataBase=Test;UID=sa;PWD=pass@123;"))
    {
        string query = "INSERT INTO Election (AdminName,ElectionName,BallotQuestion,CandidateName,Shortbio) VALUES (@AdminName,@ElectionName,@BallotQuestion,@CandidateName,@Shortbio)";
        SqlCommand cmd = new SqlCommand(query);
        cmd.Parameters.AddWithValue("@AdminName", adminName);
        cmd.Parameters.AddWithValue("@ElectionName", electtionName);
        cmd.Parameters.AddWithValue("@BallotQuestion", ballotQuestion);
        cmd.Parameters.AddWithValue("@CandidateName", name);
        cmd.Parameters.AddWithValue("@Shortbio", shortbio);
        cmd.Connection = con;
        con.Open();
        cmd.ExecuteNonQuery();
        con.Close();
    }

    Response.Redirect(Request.Url.AbsoluteUri);
}

VB.Net

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    If Not IsPostBack Then
        Dim query As String = "SELECT DISTINCT BallotQuestion FROM Election WHERE AdminName = '" &
                            Adminlbl.Text & "' AND ElectionName = '" & electlbl.Text & "'"
        Dim dt As DataTable = GetData(query)
        dlquestion.RepeatColumns = dt.Rows.Count
        dlquestion.DataSource = dt
        dlquestion.DataBind()
        dlquestion.RepeatColumns = 1
        dlquestion.RepeatDirection = RepeatDirection.Vertical
    End If
End Sub

Protected Sub dlquestion_ItemDataBound(ByVal sender As Object, ByVal e As DataListItemEventArgs)
    If e.Item.ItemType = ListItemType.Item OrElse e.Item.ItemType = ListItemType.AlternatingItem Then
        Dim BallotQuestion As String = TryCast(e.Item.FindControl("lblQuestion"), Label).Text
        Dim rptOptions As Repeater = TryCast(e.Item.FindControl("rptOptions"), Repeater)
        Dim query As String = "SELECT Id,CandidateName, Shortbio FROM Election WHERE BallotQuestion = '" &
                            BallotQuestion & "' AND AdminName = '" & Adminlbl.Text & "' AND ElectionName = '" & electlbl.Text & "'"
        rptOptions.DataSource = GetData(query)
        rptOptions.DataBind()
    End If
End Sub

Private Function GetData(ByVal query As String) As DataTable
    Dim cmd As SqlCommand = New SqlCommand(query)
    Using con As SqlConnection = New SqlConnection("Server=.;DataBase=Test;UID=sa;PWD=pass@123;")
        Using sda As SqlDataAdapter = New SqlDataAdapter()
            cmd.Connection = con
            sda.SelectCommand = cmd
            Using dt As DataTable = New DataTable()
                sda.Fill(dt)
                Return dt
            End Using
        End Using
    End Using
End Function

Protected Sub OnAddOption(ByVal sender As Object, ByVal e As EventArgs)
    Dim item As DataListItem = TryCast(TryCast(sender, Button).NamingContainer, DataListItem)
    Dim ballotQuestion As Label = TryCast(item.FindControl("lblQuestion"), Label)
    hfBallotQuestion.Value = ballotQuestion.Text
    ClientScript.RegisterStartupScript(Me.GetType(), "Popup", "ShowPopup();", True)
End Sub

Protected Sub OnAdd(ByVal sender As Object, ByVal e As EventArgs)
    Dim adminName As String = Adminlbl.Text
    Dim electtionName As String = electlbl.Text
    Dim ballotQuestion As String = hfBallotQuestion.Value
    Dim name As String = txtCandidateName.Text
    Dim shortbio As String = txtCandidateName.Text

    Using con As SqlConnection = New SqlConnection("Server=.;DataBase=Test;UID=sa;PWD=pass@123;")
        Dim query As String = "INSERT INTO Election (AdminName,ElectionName,BallotQuestion,CandidateName,Shortbio) VALUES (@AdminName,@ElectionName,@BallotQuestion,@CandidateName,@Shortbio)"
        Dim cmd As SqlCommand = New SqlCommand(query)
        cmd.Parameters.AddWithValue("@AdminName", adminName)
        cmd.Parameters.AddWithValue("@ElectionName", electtionName)
        cmd.Parameters.AddWithValue("@BallotQuestion", ballotQuestion)
        cmd.Parameters.AddWithValue("@CandidateName", name)
        cmd.Parameters.AddWithValue("@Shortbio", shortbio)
        cmd.Connection = con
        con.Open()
        cmd.ExecuteNonQuery()
        con.Close()
    End Using

    Response.Redirect(Request.Url.AbsoluteUri)
End Sub