Dialog box with options retrieved from database - c#

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);
}

Related

Drag and Drop ListBox Rows with jQuery in ASP.Net

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

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/

Copy text to clipboard using Zero Clipboard in asp.net

I am trying to use Zero *Clipboard* to copy text from Textbox to Clipboard when client clicks a Button. I am trying this for many days but no luck to make this work.
In Scenario, i have one Textbox which render data from the Database. I have one Button which when client clicks should copy text of the Textbox. I have tried following but its not working.
Some help will be appreciated.
<script type="text/javascript" src="/Scripts/ZeroClipboard.js"></script>
<script type="text/javascript">
ZeroClipboard.setMoviePath('/Scripts/ZeroClipboard.swf');
</script>
<script>
function test() {
ZeroClipboard.setMoviePath('/Scripts/ZeroClipboard.swf');
//create client
var clip = new ZeroClipboard.Client();
//event
clip.addEventListener('mousedown', function () {
clip.setText(document.getElementById('TextBox2').value);
});
clip.addEventListener('complete', function (client, text) {
alert('copied: ' + text);
});
//glue it to the button
clip.glue('d_clip_button');
}
</script>
<asp:TextBox ID="TextBox2" runat="server" BorderStyle="None" Enabled="False" Font-Size="Medium" ForeColor="Black" Width="213px"></asp:TextBox>
<asp:Button ID="d_clip_button" runat="server" Text="Copy" OnClientClick="javascript:test();" />
<html>
<body>
<button id="copy-button" data-clipboard-text="Copy Me!" title="Click to copy me.">
Copy to Clipboard</button>
<script src="ZeroClipboard.js"></script>
<script src="main.js"></script>
</body>
</html>
//In Main.js file
// main.js
var clip = new ZeroClipboard( document.getElementById("copy-button"), {
moviePath: "/path/to/ZeroClipboard.swf"
} );
clip.on( 'load', function(client) {
// alert( "movie is loaded" );
} );
clip.on( 'complete', function(client, args) {
this.style.display = 'none'; // "this" is the element that was clicked
alert("Copied text to clipboard: " + args.text );
} );
clip.on( 'mouseover', function(client) {
// alert("mouse over");
} );
clip.on( 'mouseout', function(client) {
// alert("mouse out");
} );
clip.on( 'mousedown', function(client) {
// alert("mouse down");
} );
clip.on( 'mouseup', function(client) {
// alert("mouse up");
} );
<html>
<body>
<script type="text/javascript" src="ZeroClipboard.js"></script>
<div id="d_clip_button" style="border:1px solid black; padding:20px;">Copy To Clipboard</div>
<script language="JavaScript">
var clip = new ZeroClipboard.Client();
var myTextToCopy = "Hi, this is the text to copy!";
clip.setText( myTextToCopy );
clip.glue( 'd_clip_button' );
</script>
</body>
</html>
First of all, you're trying to pick element by wrong id. Since you use webforms, correct way is:
getElementById('<%=TextBox2.ClientID%>')
Also, following unobtrusive js style good solution might look like:
$().ready(function () {
ZeroClipboard.setDefaults({ moviePath: "/Scripts/ZeroClipboard.swf" });
var clip = new ZeroClipboard(document.getElementById('YourButtonId')); //or '<%=YourButton.ClientID%>' if you use asp.net button
clip.on('complete', function (client, args) {
alert("Copied text to clipboard: " + args.text);
});
});
Also your button should have data attribute data-clipboard-target(actually there're three ways to do it). Setting data-attributes to webforms control is tricky, so you might want to avoid using asp.net button here and do it like:
<input type="button" value="clickme" id="YourButtonId" data-clipboard-target="<%=TextBox2.ClientID %>"/>
Enjoy!

Javascript function is not working on asp:button Click event, where a test alert function works.!

I am trying to create an alert as described in this site http://needim.github.com/noty/
and here is the code
<head runat="server">
<title>Test</title>
<script src="jquery-1.7.2.min.js" type="text/javascript"></script>
<script type="text/javascript" src="js/noty/jquery.noty.js"></script>
<script type="text/javascript" src="js/noty/layouts/top.js"></script>
<link rel="stylesheet" type="text/css" href="buttons.css" />
<script type="text/javascript" src="js/noty/themes/default.js"></script>
</head>
<body>
<div class="container">
<div id="customContainer">
</div>
</div>
<script type="text/javascript">
function generate(type, layout) {
var n = noty({
theme: 'defaultTheme',
text: 'Do you want to continue?',
buttons: [
{
addClass: 'btn btn-primary',
text: 'Ok',
onClick: function ($noty) {
// this = button element
// $noty = $noty element
$noty.close();
noty(
{
text: 'Record deleted !',
type: 'success',
callback:
{
onShow: function () { },
afterShow: function () { TakeValue(true); },
onClose: function () { },
afterClose: function () { }
}
});
}
},
{
addClass: 'btn btn-danger',
text: 'Cancel',
onClick: function ($noty) {
$noty.close();
noty(
{
text: 'Record not deleted !',
type: 'warning',
callback:
{
onShow: function () { },
afterShow: function () { TakeValue(false); },
onClose: function () { },
afterClose: function () { }
}
});
}
}
]
});
}
function TakeValue(result) {
if (result == true) {
document.getElementById("Hidden1").value = "true";
alert(document.getElementById("Hidden1").value);
} else {
document.getElementById("Hidden1").value = "false";
alert(document.getElementById("Hidden1").value);
}
}
function generateAll() {
generate('information', 'top');
}
</script>
<form id="form" runat="server">
<input id="Hidden1" type="hidden" value="false"/>
<asp:Button ID="Button2" runat="server" Text="Press" OnClientClick="return generateAll();" />
<input id="Button1" type="button" value="button" onclick="return generateAll();" />
</form>
</body>
I have placed two buttons ,one is HTML button while the other is of asp:Button,
The whole scenario just works fine when I use the HTML button ,but the page is not displaying the similar behavior in case of asp:Button click, I have placed a test function in JavaScript to test the OnClientClick event of the asp:Button and that worked fine,but I don't know why this alert is not getting called, I think there is some problem with the Noty JS.
Kindly give feed back
thanks.
As jbabey said in the comments:
an asp:button will cause a postback when clicked by default. you need to return false from the onclientclick, right now you are returning undefined since generateAll has no return.
Since you're using jQuery, I'd go one step further and not directly set the click attribute. Instead, set it using jQuery:
<script>
$(document).ready(function() {
$('#Button1').click(generateAll);
});
...
function generateAll(e) {
generate('information', 'top');
// This will prevent the default action of submitting the form.
e.preventDefault();
}
</script>
Could you please add UseSubmitBehavior="false" attribute to the asp:button.
<asp:Button ID="Button2" runat="server" Text="Press" UseSubmitBehavior="false" OnClientClick="return generateAll();" />
I hope this will resolve your issue. Please let me know whether it helped you or not.

Check all CheckBoxes in GridView

I have a GridView in ASP.NET/C# with a CheckBoxField, a BoundField and 2 ButtonFields. All 4 of them has a header to make clear where the column stands for. At the Page_Load event I set the ВataЫource of the GridView to my filled DataTable.
I want to make it easier to use for the user, and want to make a checkbox in the header. When that checkbox is checked by the user, all CheckBoxes should be checked in the GridView. I have set the HeaderText of the CheckBoxField to <input type='checkbox' />, and it shows a checkbox in the header now.
Now I want to add a function to that checkbox, that when it's checked, all CheckBoxes will be checked en vice versa. I tried to do it with jQuery, but it didn't work because I can't find a way to give all the CheckBoxes in the GridView the same ID or NAME.
Is there a event that occurs when I check the HTML based checkbox within the header? If yes, which event?
If no, how can i trigger a event when I check that checkbox, and change the GridView from my code-behind.
And if none of that is possible, how can i do it on another way, with javascript, jQuery or maybe with a ASP.net control.
I hope you can help me with this, but please don't expect i'm a code guru. I'm a intern at a company where the need a system, with this functionality.
Update:
Thank you everyone for helping me out. What is the easiest way to get the DataSource back into the DataTable, because i need to know which rows were selected and which were not?
Using jQuery, you get all the check boxes inside the GridView, and then for each one you change the status as you like. You call this javascript function from onclick of a link or a button, or what ever you like.
function CheckAll()
{
var updateButtons = jQuery('#<%=gvGridViewId.ClientID%> input[type=checkbox]');
updateButtons.each( function() {
// use this line to change the status if check to uncheck and vice versa
// or make it as you like with similar function
jQuery(this).attr("checked", !this.checked);
});
}
try this code according to you
in grid view
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="headerchkbox" runat="server" CssClass="chkheader" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="CheckBoxAssign" runat="server" CssClass="chkitems" />
</ItemTemplate>
</asp:TemplateField>
java script
<script type="text/javascript">
$(window).bind('load', function () {
var headerChk = $(".chkheader input");
var itemChk = $(".chkitems input");
headerChk.bind("click", function () { itemChk.each(function () { this.checked = headerChk[0].checked; })
});
itemChk.bind("click", function () { if ($(this).checked == false) headerChk[0].checked = false; });
});
</script>
Here is a sample I have put together for you.
ASPX
<head runat="server">
<title></title>
<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
var allCheckBoxSelector = '#<%=GridView1.ClientID%> input[id*="chkAll"]:checkbox';
var checkBoxSelector = '#<%=GridView1.ClientID%> input[id*="chkSelected"]:checkbox';
function ToggleCheckUncheckAllOptionAsNeeded() {
var totalCheckboxes = $(checkBoxSelector),
checkedCheckboxes = totalCheckboxes.filter(":checked"),
noCheckboxesAreChecked = (checkedCheckboxes.length === 0),
allCheckboxesAreChecked = (totalCheckboxes.length === checkedCheckboxes.length);
$(allCheckBoxSelector).attr('checked', allCheckboxesAreChecked);
}
$(document).ready(function () {
$(allCheckBoxSelector).live('click', function () {
$(checkBoxSelector).attr('checked', $(this).is(':checked'));
ToggleCheckUncheckAllOptionAsNeeded();
});
$(checkBoxSelector).live('click', ToggleCheckUncheckAllOptionAsNeeded);
ToggleCheckUncheckAllOptionAsNeeded();
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="chkAll" runat="server" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkSelected" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
</body>
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
List<string> lstObjects = new List<string> { "aaa", "bbb" };
GridView1.DataSource = lstObjects;
GridView1.DataBind();
}
}
If you are using the latest version of jQuery (1.7)
Use the following:
<script type="text/javascript">
var allCheckBoxSelector = '#<%=GridView1.ClientID%> input[id*="chkAll"]:checkbox';
var checkBoxSelector = '#<%=GridView1.ClientID%> input[id*="chkSelected"]:checkbox';
function ToggleCheckUncheckAllOptionAsNeeded() {
var totalCheckboxes = $(checkBoxSelector),
checkedCheckboxes = totalCheckboxes.filter(":checked"),
noCheckboxesAreChecked = (checkedCheckboxes.length === 0),
allCheckboxesAreChecked = (totalCheckboxes.length === checkedCheckboxes.length);
$(allCheckBoxSelector).attr('checked', allCheckboxesAreChecked);
}
$(document).ready(function () {
$(allCheckBoxSelector).click(function () {
$(checkBoxSelector).attr('checked', $(this).is(':checked'));
ToggleCheckUncheckAllOptionAsNeeded();
});
$(checkBoxSelector).click(ToggleCheckUncheckAllOptionAsNeeded);
ToggleCheckUncheckAllOptionAsNeeded();
});
</script>

Categories

Resources