Drag and Drop ListBox Rows with jQuery in ASP.Net - c#

I'm trying to implement a C# drag and drop with a listbox.
I've come across some snippets of code on the internet but none seem to be working with my needs.
I want you to show me an example code of how to move rows in ListBox.
My code below.
Thanks!
.cs
public partial class DragDrop : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string constr = ConfigurationManager.ConnectionStrings["cn"].ConnectionString;
string query = "SELECT * FROM City LIMIT 10;";
using (MySqlConnection con = new MySqlConnection(constr))
{
using (MySqlCommand cmd = new MySqlCommand(query))
{
using (MySqlDataAdapter sda = new MySqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataSet ds = new DataSet())
{
sda.Fill(ds);
ListBox1.DataSource = ds.Tables[0];
ListBox1.DataTextField = "Name";
ListBox1.DataValueField = "Name";
ListBox1.DataBind();
}
}
}
}
}
}
.aspx
<script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.8.0.js" type="text/javascript"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.22/jquery-ui.js"></script>
<link rel="Stylesheet" href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.10/themes/redmond/jquery-ui.css" />
<script type="text/javascript">
$(function () {
$(".drag_drop_grid").sortable({
items: 'tr:not(tr:first-child)',
cursor: 'crosshair',
connectWith: '.drag_drop_grid',
axis: 'y',
dropOnEmpty: true,
receive: function (e, ui) {
$(this).find("tbody").append(ui.item);
}
});
$("[id*=ListBox2] tr:not(tr:first-child)").remove();
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ListBox ID="ListBox1" runat="server"
SelectionMode="Multiple"
Height="100"
Width="100"
Font-Names="Verdana"
EnableViewState="true"></asp:ListBox>
<asp:ListBox ID="ListBox2" runat="server"
Height="100"
Width="100"
Font-Names="Verdana"></asp:ListBox>
</div>
</form>
</body>
</html>

Hope this can help you.
Best regards
http://rajudasa.blogspot.com/2011/11/drag-and-drop-list-items-with-multi.html
Here you will find information about selecting items by drag-n-drop on webpage and how i created drag-n-droppable items in listBoxes using JQuery-UI Sortable.
On JQuery-UI Sortable Demo page, List items been represented by <li>, I tried with <li> and <td> as items, both of them not satisfied my requirement. Instead of using <li> as items, I used <div> tags. One of the required feature is, multi-select drag drop using ctrl + mouse drag.
The sample demo page contains 2 Listboxes (source, destination). Source box is filled with items from JSON data(static or coming from Asp.Net). On button click, the selected/dropped items in destination box
are stored in a hidden-field as JSON string and you can retreive them at serverside. (or in JS version, just filling in a textarea).
You can check the demo here
Download the Zip file here

Related

the button is not doing its supposed function

I'm having a project to create a website that connects my database to perform different functionalities. When I create the web form and connects it with the database, and when i click the button it's supposed that all the products will appear but it doesn't happen.
This is the SQL procedure:
CREATE PROC reviewOrders
AS
BEGIN
SELECT *
FROM Orders
END
And this is the c# code
protected void reviewOrders(object sender, EventArgs e)
{
string connStr = ConfigurationManager.ConnectionStrings["MyDbConn"].ToString();
SqlConnection conn = new SqlConnection(connStr);
SqlCommand cmd = new SqlCommand("reviewOrders", conn);
cmd.CommandType = CommandType.StoredProcedure;
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
and the HTML code:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="ReviewOrders.aspx.cs"
Inherits="GUCommerce.ReviewOrders" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="viewOrders" runat="server" OnClick ="reviewOrders" Height="45px"
Text="view orders" Width="148px" />
</div>
<p style="height: 121px">
</p>
<asp:Panel ID="x" Visible ="false" runat="server" Height="338px">
<asp:Table ID="orders" CellPadding ="4" runat="server" Height="67px" Width="316px">
</asp:Table>
</asp:Panel>
</form>
</body>
</html>
Can one please tell me what is missing?
Thanks is advance!
I would recommend using ASP Gridview instead of ASP Table. Gridviews (<asp:GridView>) are used to present data in tables. They actually get rendered as html tables. Here is how to build one using your code:
<asp:Panel ID="x" Visible="false" runat="server" Height="338px">
<%--<asp:Table ID="orders" CellPadding="4" runat="server" Height="67px" Width="316px"></asp:Table>--%>
<asp:GridView ID="gvOrders" CellPadding="4" runat="server" Height="67px" Width="316px"></asp:GridView>
</asp:Panel>
Now, in the code-behind there are a couple changes. A DataTable can be used to store the results of your query and then you can bind a DataTable to a GridView. To do this, you need a SqlDataAdapter which is shown below.
protected void reviewOrders(object sender, EventArgs e)
{
// data table variable outside of sql block
// you could also move the sql code to another method that returns a datatable
DataTable dt = null;
string connStr = ConfigurationManager.ConnectionStrings["MyDbConn"].ToString();
using (SqlConnection conn = new SqlConnection(connStr))
{
SqlCommand cmd = new SqlCommand("reviewOrders", conn);
cmd.CommandType = CommandType.StoredProcedure;
using (cmd)
{
conn.Open();
// Use SQL Data Adapter instead of Execute Non Query
using (SqlDataAdapter _Adapter = new SqlDataAdapter(cmd))
{
// Fill DataTable with results of query
dt = new DataTable();
_Adapter.Fill(dt);
}
}
}
//
gvOrders.DataSource = dt;
gvOrders.DataBind();
}
Note: I use using(SqlConnection) and using(cmd) to handle closing the connection and command for me. Give this a shot.

How to add Search Functionality to a dropdownlist in asp.net using Select2.js

I have a Project with a MasterPage. I added a content page name AddEmployeeDetail.aspx which is here
<%# Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeFile="AddEmployeeDetail.aspx.cs" Inherits="DeceasedSystem.AddEmployeeDetail" %>
Inside the content page AddEmployeeDetail.aspx i have a dropdownlist called ddEmployeeName. On page load, this dropdownlist is populated from the database with EmployeeName. Here is the HTML
<div class="form-group row">
<label for="name" class="col-4 col-form-label">Employee Name</label>
<div class="col-8">
<asp:DropDownList ID="ddEmployeeName" runat="server" class="form-control here"></asp:DropDownList>
</div>
</div>
Here is the .cs file code
protected void Page_Load(object sender, EventArgs e)
{
ddEmployeeName.DataSource = LoadComboBoxEmployeeName();
ddEmployeeName.DataTextField = "Name";
ddEmployeeName.DataValueField = "Id";
ddEmployeeName.DataBind();
ddEmployeeName.Items.Insert(0, new ListItem("--Select--", "0"));
}
string CS = ConfigurationManager.ConnectionStrings["DeceasedDBCS"].ConnectionString;
//Load ComboBox Company
private DataTable LoadComboBoxEmployeeName()
{
DataTable dtFatherName = new DataTable();
using (SqlConnection con = new SqlConnection(CS))
{
using (SqlCommand cmd = new SqlCommand("SELECT Id, Name FROM TableEmployeeMaster", con))
{
cmd.CommandType = CommandType.Text;
con.Open();
SqlDataReader r = cmd.ExecuteReader();
dtFatherName.Load(r);
}
}
return dtFatherName;
}
I also add a script file in this AddEmployeeDetail.aspx content page which is:
<script>
$(document).ready(function () {
$("#ddEmployeeName").select2({
placeholder: "Select an option",
allowClear: true
});
});
</script>
and also a link of Jquery.js and Select2.js files which is
<script src="js/jquery.js"></script>
<script src="js/select2.js"></script>
Both the files are in content Placeholder.
Now I want, After the page load and data comes to the dropdownlist, when a user clicks on the dropdownlist, he/she should be able to search for any specific data and then select that. In short, I want to add search functionality to dropdownlist. So far what have I done, it is not working. It loads data but doesn't add the search functionality. I don't know what is the problem. And also, will it work if added the scripts and script files in MasterPage instead of the content Page? I am using BS4.
Help me Please.
You can just simply use:
$("#<%=ddEmployeeName.ClientID%>").select2({
placeholder: "Select an option",
allowClear: true
});
Try to Set DropDownList's ClientIDMode property to Static.

How to enable the dropdown list on a specific radio button

I am trying to enable the dropdown list when the user select the radio button with a id =9, for some reason the jquery function is not working
For debugging purpose, i've tried to alert the selected id but it's null
Any thoughs?
C# code
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
string constr = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
using (MySqlConnection con = new MySqlConnection(constr))
{
string query = "SELECT * FROM case_cat_lv1";
using (MySqlCommand cmd = new MySqlCommand(query))
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
rblFruits.DataSource = cmd.ExecuteReader();
rblFruits.DataTextField = "category_name";
rblFruits.DataValueField = "id";
rblFruits.DataBind();
con.Close();
}
}
}
}
ASP.NET .aspx
<form id="form1" runat="server">
<div>
<asp:RadioButtonList ID="rblFruits" runat="server" OnCheckedChanged="air_CheckedChanged" class="radio">
</asp:RadioButtonList>
<br />
<asp:Button ID="btnSubmit" Text="Submit" runat="server" OnClick="Submit" />
<asp:DropDownList ID="airlist" runat="server" Font-Size="20px" class="dropdown">
<asp:ListItem>Air India</asp:ListItem>
<asp:ListItem>Kingfisher</asp:ListItem>
<asp:ListItem>Jet Airways</asp:ListItem>
<asp:ListItem>Spice Jet</asp:ListItem>
</asp:DropDownList>
</div>
<script>
$(document).ready(function () {
$('.dropdown').attr("disabled", true);
$('#rblFruits').change(function () {
alert($(this).val());
if ($(this).val() == '9') {
$('.dropdown').attr("disabled", false);
}
else {
$('.dropdown').attr("disabled", true);
}
//alert($(this).val());
});
});</script>
</form>
Try $(this).find(":checked").val(); instead of $(this).val(). And if you want id of selected radio button then $(this).find(":checked").attr("id").
To enable dropdown list you can remove attribute disabled. It should work.
$('.dropdown').removeAttr("disabled");
For disabling your code will work fine.
$('.dropdown').attr("disabled", true);
A few of things to consider. ASP.net webforms can mangle ids, RadioButtonList is not an HTML entity and is rendered as radio buttons with their own ids and values, finally you also have OnCheckedChanged="air_CheckedChanged" as a server side event handler which could be causing you problems.
With these kinds of issues with .net WebForms, always check the rendered HTML to see if it is what you were expecting.
Here's how I'd do it:
<form id="form1" runat="server">
<div>
<!-- I've taken out the server side event handler -->
<asp:RadioButtonList ID="rblFruits" runat="server" class="radio">
</asp:RadioButtonList>
<br />
<asp:Button ID="btnSubmit" Text="Submit" runat="server" OnClick="Submit" />
<asp:DropDownList ID="airlist" runat="server" Font-Size="20px" class="dropdown">
<asp:ListItem>Air India</asp:ListItem>
<asp:ListItem>Kingfisher</asp:ListItem>
<asp:ListItem>Jet Airways</asp:ListItem>
<asp:ListItem>Spice Jet</asp:ListItem>
</asp:DropDownList>
</div>
<script>
$(document).ready(function () {
$('.dropdown').attr("disabled", true);
/*#rblFruits will be a container, not actual radio buttons*/
/*Keeping in mind name mangling, get the actual client ID.
Note that if you're putting thing in an external js file,
you'll need to come up with another plan*/
$('#<%=rblFruits.ClientID%> input[type=radio]').change(function () {
alert($(this).val());
$('.dropdown').prop("disabled", $(this.val() !== '9'));
});
});</script>
</form>
See also: http://api.jquery.com/prop/

Dialog box with options retrieved from database

I have a database table Prospect which stores prospects with primary key id & version. There is a radbutton Generate Proposal in a webform, which when clicked should display a dialog box to allow the user to select the version of the prospect to generate from a dropdown box. I have a method which will retrieve the versions from the database for the prospect GetVersions() but have no idea how to put it in a dialog box to allow the user to select the version. Any help is greatly appreciated.
Would JQuery UI be an option?
You would have to add the JQuery UI refferences which can be found Here
Here is the documentation on the JQuery UI dialog.
The below code was taken from a solution that I implemented. I have removed quite a few pieces of code for simplicity. Let me know if you need any clarification.
HTML:
<div id="MenuChangeSelection" title="Change Selection" class="MainDialog">
<div id="MenuChangeSelectionContent"></div>
</div>
JQuery:
$("#YourRadBtnID").click(function () {
var yourDropDownMarkup = "<select><option value='Opt1'>Opt1</option></select>"; // Insert your dropdown markup or get your dropdown from the dom.
$("#MenuChangeSelectionContent").html(yourDropDownMarkup);
$("#MenuChangeSelection").dialog({
autoOpen: true,
modal: true,
width: 600,
height: 150,
buttons: {
"Save And Close": function() {
//Do something when Save And Close is clicked. eg. asynchronously post back to server.
},
"Cancel": function() {
$(this).dialog("close");
}
},
open: function () {
$('.ui-widget-overlay').addClass('custom-overlay');
},
close: function () {
$('.ui-widget-overlay').removeClass('custom-overlay');
}
});
});
CSS:
.ui-widget-overlay.custom-overlay
{
background-color:black;
opacity:0.4;
filter:alpha(opacity=40); /* For IE8 and earlier */
}
Here a little snippet to get you started. This uses the jQuery Dialog Box.
In the aspx page
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<asp:Button ID="generateProposal" runat="server" Text="Generate Proposal" OnClick="generateProposal_Click" />
<div id="popupContent" style="display: none">
<asp:DropDownList ID="DropDownList1" runat="server"></asp:DropDownList>
<br />
<br />
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click1" />
</div>
<script type="text/javascript">
function showPopup() {
$(function () {
$("#popupContent").dialog();
});
}
</script>
And then in code behind.
protected void generateProposal_Click(object sender, EventArgs e)
{
//the id of the prospect. Not clear from your question where this should come from
int proposalID = 6;
//sometimes a counter is just a counter
int counter = 0;
//clear old items from the dropdownlist
DropDownList1.Items.Clear();
//load the prospects from the database here and attach to dropdownlist
using (SqlConnection connection = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand("prospect_select", connection))
{
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("#id", SqlDbType.Int).Value = proposalID;
try
{
//open the database connection
connection.Open();
SqlDataReader reader = command.ExecuteReader();
//loop all rows and add them to the dropdownlist
while (reader.Read())
{
DropDownList1.Items.Insert(counter, new ListItem(reader["prospect_name"].ToString(), reader["prospect_version"].ToString(), true));
counter++;
}
}
catch (Exception exception)
{
//handle the error if you want
}
}
//call the javascript function to open the dialog box
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "showPopup", "showPopup();", true);
}

AutoCompleteExtender on TextBox returns the page HTML

I am trying to implement a search textbox with the Ajax Control Toolkit AutoCompleteExtender. The result should be a list of names matching the entered text however what gets displayed is the page source HTML, character by character, creating an extremely long list of single letters.
I have found and tried several samples but cannot get this to work. I am certain the database connection is valid and the SQL query when executed directly in MSSMS, returns the expected result. The AjaxControlToolkit is installed and works on other pages in the solution.
This issue was asked before ("Ajax Control Toolkit AutoCompleteExtender displays html source character by character of the current page as autocomplete suggestion list"). However for reasons of simplicity and maintainability I do not want to implement a WebService as this poster did.
acex.aspx
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>AutoCompleteExtender - Last Names</title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<div>
<asp:TextBox ID="txbxLastName" runat="server"></asp:TextBox>
<asp:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server"
TargetControlID="txbxLastName"
MinimumPrefixLength="2"
EnableCaching="true"
CompletionSetCount="1"
CompletionInterval="1000"
ServiceMethod="GetLastNames">
</asp:AutoCompleteExtender>
</div>
</form>
</body>
</html>
acex.aspx.cs
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
namespace MCA
{
public partial class acex : System.Web.UI.Page
{
[System.Web.Script.Services.ScriptMethod()]
[System.Web.Services.WebMethod]
public static List<string> GetLastNames(string prefixText)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString());
SqlCommand cmd = new SqlCommand("SELECT [Last_Name] FROM [Entity_Person] WHERE [Last_Name] LIKE #Name+'%'", conn);
cmd.Parameters.AddWithValue("#Name", prefixText);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
conn.Open();
da.Fill(dt);
List<string> LastNames = new List<string>();
for (int i = 0; i < dt.Rows.Count; i++)
{
LastNames.Add(dt.Rows[i][0].ToString());
}
return LastNames;
}
}
}

Categories

Resources