How to add a dropdownlist that’s dynamically populated from database to each row in datatable gridview

So I’ve created a fully functional gridview that has the two last columns as dropdownlists that are populated from the database and they read/write from it. But I needed to implement search unto the gridview so I used the Datatables.net plugin, It works perfectly but as soon as I add the drop down lists, the search is disabled. Unless I add them through javascript and I’m not nearly experienced enough in that field to accomplish that on my own.

Before I switched to the datatable plug in, I used to just append the dropdownlists I needed at the Rowdatabound event of the gridview, How can I achieve something similar through javascript ?

This is the java script code :

var TableContent = "<tr>";

if (!$("#req").length) 
    $("body").append("<table id='req'></table>");
else 
    $('#req').prepend($('<thead>').append($('.add_ADU')));


var colns = [

{ "data": "Request_ID", title: "ID", },
{ "data": "Student_ID", visible:true },
{ "data": "Type", visible:true },
{ "data": "Description", visible:true },
{ "data": "Language", visible:true },
{ "data": "PUC", visible:true },
{ "data": "Quantity", title: "Quantity" },
{ "data": "Comments", title: "Comments" },
{ "data": "Fees", title: "Fees" },
{ "data": "Date", title: "Date" },
{ "data": "Payment_Status", title: "Payment Status" },
{ "data": "Payment_Date", title: "Payment Date" },
{ "data": "Student_Name", title: "Student Name", visible:true },
{ "data": "Payment_ID",title:"Payment ID", title: "Phone" },
{ "data": "Addressed_To",title: "Addressed To", visible:true },
{ "data": "username", title:"Assigned To",visible:true },
{ "data": "status", title:"Status",visible:true }

];

var table = $('#req').DataTable({
    select: true,

    "columns": colns,
    "order": [[ 12, "desc" ]],
    "initComplete": function (settings, json) {
        reset_table_page_length($(window).height());
    },

});


$("#req tr").append(
    '<select id="assign"' +
    '<option value="Paid">him</option>' +
    '<option value="NotPaid">her</option>' +
    '</select>'
)


$("#req_filter").prepend(
    '<select id="inp-sel-status-fltr" class="table-toolbar-inp">' +
        '<option value="Paid">Paid</option>' +
    '<option value="NotPaid">Not Paid</option>'+ 
    '</select>'
    )


$("#inp-sel-status-fltr").change(function myfunction() {
    filter_table_by_status($(this).val());
});




function filter_table_by_status(val) {
    table.column(10).search(val);
    table.draw();
}

As pathetic as it is, this is how far I’ve gotten to achieving what I’m trying to :

$("#req tr").append(
'<select id="assign"' +
'<option value="Paid">him</option>' +
'<option value="NotPaid">her</option>' +
'</select>')

This is the HTML code for the gridview :

   <div class="container">
            <asp:GridView BorderWidth="0" CssClass="stripe compact order-column row-border" runat="server" AutoGenerateColumns="true" ID="req" OnRowDataBound="req_RowDataBound" ClientIDMode="Static" Style="width: 100% !important">
                <HeaderStyle CssClass="add_ADU" /> 
            </asp:GridView>

and in the code behind I would just append the dropdownlists and then query the data I needed and populate them with it using this code:

protected void req_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            DataTable table = new DataTable();
            var openCloseddl = e.Row.FindControl("openCloseddl") as DropDownList;
            var assignddl = e.Row.FindControl("assignToddl") as DropDownList;
            assignddl.DataMember = "username";
            assignddl.DataValueField = "username";
            assignddl.DataSource = table;


            //get the values of the conditions that define which staff 
            var request_id = e.Row.Cells[0].Text;
            var type = e.Row.Cells[3].Text;
            var description = e.Row.Cells[4].Text;
            var puc = e.Row.Cells[6].Text;
            var quantity = e.Row.Cells[7].Text;



            //fetch which staff member it's assigned to if exists.
            SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["studentOrderUpload"].ConnectionString);

            SqlCommand comm = new SqlCommand("SELECT username from request_status WHERE request_id = @request_id and type = @type and description = @description and puc = @puc and quantity = @quantity", conn);
            comm.Parameters.AddWithValue("@request_id", request_id);
            comm.Parameters.AddWithValue("@type", type);
            comm.Parameters.AddWithValue("@description", description);
            comm.Parameters.AddWithValue("@puc", puc);
            comm.Parameters.AddWithValue("@quantity", quantity);

            try
            {
                conn.Open();
                object result = comm.ExecuteScalar();

                string resultText = (result == null ? "" : result.ToString());
                conn.Close();

                //if it's not assigned to anyone, show every staff member.
                if (resultText == "")
                {
                    if (type.ToLower().Contains("customized"))
                    {
                        SqlCommand cmd1 = new SqlCommand("select username from staff where type = 'customized'", conn);
                        conn.Open();
                        SqlDataAdapter ad1 = new SqlDataAdapter(cmd1);
                        ad1.Fill(table);
                        conn.Close();
                        assignddl.DataBind();
                        assignddl.SelectedValue = "Scholarship";
                        if (openCloseddl.SelectedValue == "Open")
                        {
                            openCloseddl.Enabled = true;
                        }
                        assignddl.Items.RemoveAt(1);
                    }
                    else
                    {
                        SqlCommand cmd1 = new SqlCommand("select username from staff where type ='standard'", conn);
                        conn.Open();
                        SqlDataAdapter ad1 = new SqlDataAdapter(cmd1);
                        ad1.Fill(table);
                        conn.Close();
                        assignddl.DataBind();
                    }
                    assignddl.Items.Insert(0, new ListItem("Select User"));
                    openCloseddl.Enabled = false;
                    if (openCloseddl.SelectedValue == "Open" && type.ToLower().Contains("customized"))
                    {
                        openCloseddl.Enabled = true;
                    }
                }
                //if it's assigned to someone, show only the assigned staff,
                else
                {
                    if (type.ToLower().Contains("customized"))
                    {
                        SqlCommand cmd1 = new SqlCommand("select username from staff where type = 'customized'", conn);
                        conn.Open();
                        SqlDataAdapter ad1 = new SqlDataAdapter(cmd1);
                        ad1.Fill(table);
                        conn.Close();
                        assignddl.DataBind();
                        assignddl.SelectedValue = "Scholarship";
                        if (openCloseddl.SelectedValue == "Open")
                        {
                            openCloseddl.Enabled = true;
                        }
                        assignddl.Items.RemoveAt(1);
                    }
                    else
                    {
                        SqlCommand cmd1 = new SqlCommand("select username from staff where type = 'standard'", conn);
                        conn.Open();
                        SqlDataAdapter ad1 = new SqlDataAdapter(cmd1);
                        ad1.Fill(table);
                        conn.Close();
                        assignddl.DataBind();
                        assignddl.SelectedValue = resultText;
                    }


                }





                if (openCloseddl != null)
                {

                    SqlCommand comm1 = new SqlCommand("SELECT status from request_status WHERE request_id = @request_id and type = @type and description = @description and puc = @puc and quantity = @quantity", conn);
                    comm1.Parameters.AddWithValue("@request_id", request_id);
                    comm1.Parameters.AddWithValue("@type", type);
                    comm1.Parameters.AddWithValue("@description", description);
                    comm1.Parameters.AddWithValue("@puc", puc);
                    comm1.Parameters.AddWithValue("@quantity", quantity);


                    conn.Open();
                    object result1 = comm1.ExecuteScalar();
                    conn.Close();

                    if (result1.ToString() == "Closed")
                    {

                        openCloseddl.SelectedValue = "Closed";
                        openCloseddl.Enabled = false;
                        assignddl.Enabled = false;
                        if ((HttpContext.Current.User.Identity.Name.Equals("DocRequestAdmin")))
                        {
                            assignddl.Enabled = true;
                            openCloseddl.Enabled = true;
                        }
                    }
                }



            }
            catch (Exception ee)
            {
                var error = ee.Message;
                conn.Close();
            }

            var paid = e.Row.Cells[12].Text;
            if (paid.Contains("Not"))
            {
                assignddl.SelectedValue = "Select User";
                assignddl.Enabled = false;
                openCloseddl.Enabled = false;
            }
        }
    }

Which is irrelevant at this point I believe, since I’m trying to do this through javascript.

This is a screenshot of what the grid looks like, the dropdown lists I want to add should exist in the last two columns “Assigned To” and “Status”

enter image description here

1 Answer

There is a built in render function in data tables which you can call in your columns objects.
The function accepts 3 arguments, the first one is the value of the property which you specified in your “data” property, and the third will return the value of the whole underlying object.

You can read about it here.

For example:

     { 
       "data": "username",
       title:"Assigned To",
       visible:true, 
       render: function(data, type, row) { 
        //do sth here 
       } 
     }

In the above render function, the data parameter will return the value of the “username” property, and the row parameter will return the value of all properties of the underlying object.

You can use the data provided by the row parameter to append a value and an id to your dropdown list.
If your row parameter returns an array of objects, you can do a for loop to iterate and append every value to the select element.

Archive from: https://stackoverflow.com/questions/59015626/how-to-add-a-dropdownlist-thats-dynamically-populated-from-database-to-each-row

Leave a Reply

Your email address will not be published. Required fields are marked *