How to get the order of dynamically created DropDownLists - c#

I've created some drop down lists using JavaScript, ASP.NET.
A user can add as many drop down lists as he wants by clicking a "+" button and removing them by clicking a "-" button.
If it's hard to understand what I mean pls see " How to implement a list of dropboxes in C# ".
And now I'd like to implement the code behind and want to define the order of the drop down lists, but I don't know which one is my first drop down list, etc.
We assume that all <asp:DropDownList> contain the following for list elements: method1, method2, method3 and method4. If a user selects an element, a method in the codebehind is implemented.
Example:
dropboxlist1: select list item method2,
dropboxlist2: select list item method1,
dropboxlist3: select list item method3,
string txt= "";
if (dropboxlistID.Text == "method1"){
txt = method1Imp();
} else if (dropboxlistID.Text == "method2") {
txt = method2Imp();
} else if (dropboxlistID.Text == "method3") {
txt = method3Imp();
} else {
}
But at this moment I don't have any idea which drop down lists came first and which method should be performed on my string first.

Try enqueueing each method into a queue as a delegate, then draining (invoking each delegate) the queue once you're ready from a single thread. This will ensure that the order of execution matches the order of user choices.
Sorry I didn't initally include code. Here's a basic example to get you started:
Queue<Func<string>> actions = new Queue<Func<string>>();
if(dropboxListID.Text =="m1")
{
actions.Enqueue(method1Imp);
}
if(dropboxListID.Text = "m2")
{
action.Enqueue(method2Imp);
}
...
Sometime Later when you're ready to process these
...
string txt = "";
while(actions.Count >0)
{
var method = actions.Dequeue();
txt = method();
}
Here's a blog post that delves further into the concept of a work/task queue:
http://yacsharpblog.blogspot.com/2008/09/simple-task-queue.html

IMO your drop down lists will be contained in a parent.
Let us say (acc to your link) your parent is DropDownPlaceholder.
<div id="DropDownPlaceholder">
Use linq to get all children of it. Cast them as drop down lists and then your can loop on them to find your matter.

To get the order of dropdownlists:
First set the IDs/ClientIDs of hard-coded dropdownlists in aspx page and
count them (say 2 dropdownlists are present)
While creating dropdownlists dynamically, append a count integer at
the end of their IDs/ClientIDs like ddl3, ddl4 (start the count from 3)
Then in your code, you can find the dropdownlist of selected element:
if (ddl.ClientID.EndsWith("1")){
// 1st ddl
} else if (ddl.ClientID.EndsWith("2")) {
// 2nd ddl
} else if (ddl.ClientID.EndsWith("3")) {
// 3rd ddl
}
...

Related

Saving a reordered List item from an MVC View Model

I have a view model which binds to a 'TreasureHuntDetails' object, which contains a list of clues. Here's part of the data model for it.
public TreasureHuntDetails()
{
Clues = new List<Clue>();
}
[Key]
public int TreasureHuntId { get; set; }
public List<Clue> Clues { get; set; }
On the page, I have a table. A foreach loop iterates through the list of clues to add them to the table, e.g.
#for (int i = 0; i < Model.Clues.Count; i++)
The table elements inside the for loop are quite large, but here's an example of one of the table element columns:
<td>#Html.DisplayFor(m => Model.Clues[i].Location)</td>
All well and good so far. Then I'm using JQuery UI to allow the items of the table to be reordered using drag and drop, like this:
<script type="text/javascript">
$(document).ready(function()
{
$("#clueTable tbody").sortable().disableSelection();
});
</script>
All well and good, I can drag and drop the elements.
The problem is that I don't know how to save the new order of elements and save them back to the database.
The first thing I tried was simply passing the list of clues to a controller method, but I found that once the list of clues reached the controller method, it was always null.
For example:
#Url.Action("ViewCluePage", #Model.Clues)
Even if I send the whole #Model, list of clues within is always null. Removing the new list instantiation from the constructor of the data model didn't solve this problem.
Another thing I tried was wrapping the whole table into a HTML form, but still the list of clues remains null.
So basically, this question is really two questions:
1) Why is the list of clues always null after sending the model object to a controller.
2) How to save the new order of the list of items?
UPDATE: As per suggestion by #recursive, I see where I made an error when trying to submit the clue elements to the HTML form.
I used this outside the for loop which iterated over the clue elements:
#Html.HiddenFor(m => m.Clues)
I had to add the HiddenFor lines inside of the for loop (for each clue item), and for EACH property of the clue item, e.g.
#Html.HiddenFor(m => m.Clues[i].Id)
So that would be one step forward to be able to get the list items sent to the controller, but I think I still need code that will reflect the new order of the clue items when sent to the controller. Currently, on rearranging the order of the elements on screen using the JQuery sortable() method, this doesn't change the order of the elements as they are stored in the data model binded to the view (#Model.Clues).
1) As #resursive said in his comment, you need to have hidden elements on the page that map to properties in your Clue class.
2) As for persisting the order of clues, you'll need to add a column to your database that holds the position of each clue in the list and add the position property to your class. So your class would need to include
public int Position {get;set;}
which should pull from the database when the page is created. Then just before rendering the page, you should reorder the clue list based on the Position variable.
Edit: Use jquery's sortable attribute. Check out this thread for reference. In the stop drag event (or right before your submit), loop through each of your draggable objects and set the value of each of the hidden Position properties of your objects.
var positionIndex = 0;
$('.draggableObjectClass).each(function () {
$(this).find('input[id$=_Position]').val(positionIndex++);
});
but I think I still need code that will reflect the new order of the clue items when sent to the controller.
You won't, as you are now iterating over them in a for loop, they will be indexed in the order that you sent them to the view. Your order must already be maintained.
Taking advice from the answers posted here already, I came up with the following solution.
With already having this method in place to implement the drag and drop reordering of the UI elements,
$(document).ready(function()
{
$("#clueTable tbody").sortable().disableSelection();
});
I needed a way to be able read the in the new order of items and send it to the MVC controller. To do this I used the Razor #Html.AttributeEncode method to write the Id's of each item to a column on each row of the table, like this:
<td class="Ids" id="#Html.AttributeEncode(Model.Clues[i].Id)">#{var number = i + 1; #number}</td>
(This is wrapped around a for loop which iterates through the list of items.)
Then, I created the following Javascript function, which is invoked from a 'SaveNewOrder' button I placed above my table of elements (the user presses this once they have finished reordering the items on the table):
function getNewOrder()
{
var positions = new Array();
for (var i = 0; i < $('.Ids').length; i++)
{
positions[i] = $('.Ids')[i].id;
}
$.ajax(
{
type: "POST",
url: "#Url.Action("ReorderClues", "Clues")",
data:{ treasureHuntDetails: $("form").serialize(), ids: JSON.stringify(positions) }
contentType:'application/json'
}).done(function()
{
window.location.href = '#Url.Action("Clues", Model)';
}).
}
What this is does is reads the Id elements from each of the table items, and writes them into the array - so this array contains the NEW order of Id's. The data model containing the items doesn't change after reordering the table elements, hence why this was necessary.
It then uses a JQuery Ajax method to invoke a 'ReOrderClues' method on my 'Clues' MVC controller, passing a serialised version of the data model (containing a list of the clue items in the original order) and an array containing a list of the clue Id's in the new order. When the result is returned from the controller (.done), I invoke a controller which refreshes the page elements.
So rather than having to maintain a position value associated with each clue (which would involve significant refactoring elsewhere in the code), what I'm doing is swapping the contents of the clues around to reflect the new order, but keeping the Id's in the same position.
This is how I achieved that using an MVC Controller:
public ActionResult ReorderClues(TreasureHuntDetails treasureHuntDetails, int[] ids)
{
using (var db = new TreasureHuntDB())
{
var clues = treasureHuntDetails.Clues;
var newClues = NewOrderList(clues, ids);
// Save the changes of each clue
for (var i = 0; i < newClues.Count;i++ )
{
db.Entry(clues[i]).CurrentValues.SetValues(newClues[i]);
db.SaveChanges();
}
treasureHuntDetails.Clues = newClues;
TempData["Success"] = "Clues reordered";
}
return RedirectToAction("Clues", treasureHuntDetails);
}
public List<Clue> NewOrderList(List<Clue> clues, int[] ids)
{
var newClueOrder = new List<Clue>();
// For each ID in the given order
for (var i = 0; i < ids.Length; i++)
{
// Get the original clue that matches the given ID
var clue = clues.First(clue1 => clue1.Id == ids[i]);
var newClue = Clue.Clone(clue);
// Add the clue to the new list.
newClueOrder.Add(newClue);
// Retain the ID of the clue
newClueOrder[i].Id = clues[newClueOrder.Count - 1].Id;
}
return newClueOrder;
}
In the above code snippet, TreasureHuntDB is my Entity Framework database context.

C# Selecting first row in CategorizedAlphabetical sorted ProperyGrid

I have ProperyGrid loaded with categorised PropertySpec and set to CategorizedAlphabetical sort. When form runs categories then items within categories are sorted. An annoying artefact is that PropertyGrid by default selects the first item after list was sorted and sometimes it scrolls view to selection. If item list is long you end up seeing list scrolled to somewhere in the middle.
Since PropertySpec can be created at runtime I want to always show the top of list on form load. PropertyGrid does not 'easily' expose collections and certainly not in ordered sequence. After googling around I am lead to believe this is not possible?
I came up with below code which proves otherwise.
Snippet will select fist category of sorted list. One could also select first item in that category expanding on the method but for my needs that was unnecessary.
// bind the PropertyTable to PropertyGrid
this.pg_Prefs.SelectedObject = proptable;
// get selected item
GridItem gi = this.pg_Prefs.SelectedGridItem;
// get category for selected item
GridItem pgi = gi.Parent.Parent;
//sort categories
List<GridItem> sortedCats = new List<GridItem>(pgi.GridItems.Cast<GridItem>());
sortedCats.Sort(delegate(GridItem gi1, GridItem gi2) { return gi1.Label.CompareTo(gi2.Label); });
// loop to first category
for (int i = 0; i < pgi.GridItems.Count; i++)
{
if (pgi.GridItems[i] == gi) break; // in case full circle done
// select if first category
if (pgi.GridItems[i].Label == sortedCats[0].Label)
{
pgi.GridItems[i].Select();
break;
}
}
Hope this will help others as well.
The simplified method of actually selecting category once you have sorted list would be to sortedCats[0].Select(); instead of looping through and checking each item. You would have to assert the list is not empty if you wanted to use that shortcut but that would gives some performance improvement...

How do I obtain selected rows in a DataGridView from different pages

I have a windows forms DataGridView, where I have data and a checkbox for each row.
I will select check box for a particular row and all the selected rows will be populated in another page.
if (grdEmp.Rows.Count > 0)
{
var selectedEmpIDs= from DataGridViewRow coll in grdEmp.Rows
where Convert.ToBoolean(coll.Cells["Select"].Value) == true
select coll;
if (selectedEmpIDs.Count() > 0)
{
foreach (DataGridViewRow row in selectedEmpIDs)
{
selectedEmp+= row.Cells["EmpId"].Value + ",";
}
}
}
This works good only for one page.
When I navigate to another page, and click the selected rows, the previous one goes off.
How do I resolve it.
Thanks
cmrhema
Note :Sorry for the confusion, When I meant it works good for a page, I meant paging.
I think I need to add more inputs,
There are 10 pages in the gridview.
I select the first record from each page of the gridview, one after another by clicking next page( Page next button).
But only the record that was selected the last is getting displayed and others and ignored off.
What could be the prblm
You can use a List or Dictionary or any other collection type globally, using Program.cs or using a static class. And store the selected rows into the list before you leave the page.
Rather than using a comma delimited string string for your list of ids you can instead use a List.
Your code will then become something like this:
if (grdEmp.Rows.Count > 0)
{
var selectedEmpIDs= from DataGridViewRow coll in grdEmp.Rows
where Convert.ToBoolean(coll.Cells["Select"].Value) == true s
select coll;
if (selectedEmpIDs.Count() > 0)
{
foreach (DataGridViewRow row in selectedEmpIDs)
{
if (!listOfIds.Contains((int)row.Cells["EmpId"].Value))
{
listOfIds.Add(((int)row.Cells["EmpId"].Value));
}
}
}
}
You will need methods to remove items from this list so adding event handlers for the checkbox selected event will probably work better.
The List object itself can simple live as a class level object of the form that containst your DataGridView.
This gets a little bit more complicated if you are managing your paging across forms, but the same principles of maintaining a list of selected ids applies.

c# linkedlist how to get the the element that is before the last element

i try to implement a redo undo in my windows form application.
i build a linkedlist , every entery of the list is a class that save the state of all the elemnts in the form.
every click on the save button , insert to this list the last state of the form elements.
when the user click on undo button i want to get the entery of the list (one before the last)
and load it.
i dont know what is the simple way to get this one before elemnts from the linked list ?
my code like look like:
public class SaveState {
public int comboBox1;
public int comboBox2;
..........
public SaveState() {
.......
}
}
LinkedList<SaveState> RedoUndo = new LinkedList<SaveState>();
# in save function
var this_state = new SaveState();
this_state = getAllState();
RedoUndo.AddLast(this_state);
# when click undo
var cur_state = new SaveState();
# this lines dont work !!!!!!!!!
int get = RedoUndo.Count - 1;
cur_state = RedoUndo.Find(get);
setAllState(cur_state);
You can get the last node via LinkedList<T>.Last
// list is LinkedList<T> for some T
var last = list.Last;
and the penultimate node via LinkedListNode<T>.Previous
var penultimate = last.Previous; // or list.Last.Previous;
Note that this is a LinkedListNode<T> and you need to use the LinkedListNode<T>.Value property get the underlying instance of T.
Of course, you should take care to check that list is not null, and list.Last is not null (in the case of an empty list), and that list.Last.Previous is not null (in the case of a single-element list).
#Haim, you may want to check out Krill Osenkov's Undo Framework. It makes undo/redo very easy.

Setting default item in combo box

I have a function for setting items in a combobox and one item is to be set by default like
--SELECT LIST--
public void SetOperationDropDown()
{
int? cbSelectedValue = null;
if(cmbOperations.Items.Count == 0)
{
//This is for adding four operations with value in operation dropdown
cmbOperations.Items.Insert(0, "PrimaryKeyTables");
cmbOperations.Items.Insert(1, "NonPrimaryKeyTables");
cmbOperations.Items.Insert(2, "ForeignKeyTables");
cmbOperations.Items.Insert(3, "NonForeignKeyTables");
cmbOperations.Items.Insert(4, "UPPERCASEDTables");
cmbOperations.Items.Insert(5, "lowercasedtables");
//ByDefault the selected text in the cmbOperations will be -SELECT OPERATIONS-.
cmbOperations.Text = "-SELECT OPERATIONS-";
}
else
{
if(!string.IsNullOrEmpty("cmbOperations.SelectedValue"))
{
cbSelectedValue = Convert.ToInt32(cmbOperations.SelectedValue);
}
}
//Load the combo box cmbOperations again
if(cbSelectedValue != null)
{
cmbOperations.SelectedValue = cbSelectedValue.ToString();
}
}
Can anyone suggest a way to do this?
I've rewritten this answer to clarify some stuff.
First, the "default" text must be added as combo item as well.
Usage of combo.Text property just adds descriptive text to combobox which is "lost" first time user do something with a control.
If you like to permanently have "default" text in your combo, you must add it as an combobox item.
By the code you provided, just modify the
cmbOperations.Text = "-SELECT OPERATIONS-"; to
cmbOperations.Items.Insert(0, "-SELECT OPERATIONS-");
Note that this way you add the item "-SELECT OPERANDS-" to the 0th (read first) position in the list.
Also make sure that all your following items are increased by 1, because they are now moved by one space down in list.
Finally, put cboOperations.SelectedIndex = 0; line at the end of code. By doing so, you're telling combobox to display your "default" item initially when the form (or control) loads.
One more thing. I'm not pretty sure what do you want to achieve with the code beyond setting combo items, but if you like to check what user selected use cboOperations.SelectedIndex property which contains currently selected item in combo. You can add simple if(cboOperations.SelectedIndex == someIntValue){...}
The rest is your program logic ;)

Categories