I have multiple select listbox, i want to restrict the user when he selects more than 3 values. The values can be country or cities, they are coming from database. The code for same is written in lstArea_SelectedIndexChanged method.
<asp:ListBox ID="lstArea" runat="server" SelectionMode="Multiple" OnSelectedIndexChanged="lstArea_SelectedIndexChanged" AutoPostBack="true"></asp:ListBox>
I found jquery code to validate the same, but the change function is not working.
var limit = 3;
$("#<%=lstArea.ClientID%>").change(function () {
if ($(this).siblings(':checked').length >= limit) {
this.checked = false;
}
});
I think this address can help you
https://stackoverflow.com/a/27490795/5631805
Maybe you should instead of
if ($(this).siblings(':checked').length >= limit)
this
if($('#lstArea:checked').length >= limit)
Because you have set the property AutoPostBack to true, and you have also set the OnSelectedIndexChanged event handler, .NET will generate onchange attribute for your select which will trigger POST back to the server, whenever an item will be selected. To prevent that you need to change your .NET code to this:
<asp:ListBox ID="lstArea" runat="server" SelectionMode="Multiple"/>
and also update your javascript code to this:
// Handle for the list
var list = $("#<%=lstArea.ClientID%>");
// Our limit
var limit = 3;
// Get currently selected values
var selected = list.val();
// Handle change event
list.change(function () {
// If we reached the limit
if (list.find(":checked").length >= limit) {
// Set the list value back to the previous ones
list.val(selected);
return;
}
// Postback to the server
setTimeout("__doPostBack('<%=lstArea.ClientID%>','')", 0);
});
Each time the page will be rendered the selected variable will hold the last selected items. Than in the change handler you will get all the selected/checked options, and when the count of the newly selected options is more than or equal to your limit you will unselect the last selected value by setting back all previous values. And if the limit is ok, you will made your postback, by calling the .NET function __doPostBack.
Related
I've not really used the MPE before & currently have a need to, what I'm slightly confused about is losing reference to the initial control that triggers the function.
I have a gridview with a dropdownlist and onselectedindexchanged set to call a function when a value has been selected, when processed one value i grab is the RowID into a variable, out of 9 list items only one requires the pop up (Ok = proceed & Cancel = Return) & when this is triggered I lose all reference to the given grid row which is referenced via;
DropDownList ddlid = (DropDownList)sender;
GridViewRow gvrow = (GridViewRow)ddlid.NamingContainer;
RowID = (Int32.Parse(GridView1.DataKeys[gvrow.RowIndex].Values[0].ToString()));
Can anyone shed any light or have an idea on how I can keep track of the gridview row?
Thanks
IchBinDicky
Used session object in the code behind (point of loss) in the end as it fit a few other issues I'd encountered at the same time;
public static string TabIndxValue
{
get
{
object value = HttpContext.Current.Session["TabIndxValue"];
return value == null ? "" : (string)value;
}
set
{
HttpContext.Current.Session["TabIndxValue"] = value;
}
}
My application contains a ComboBox that the user can delete items from. When the program starts up it populates the ComboBox from a list of strings read in from a configuration file.
Here is the code to add items:
// version list is an array of strings
foreach (string version in versionList)
{
versionComboBox.Items.Add(version);
}
if (versionComboBox.Items.Count > 0)
{
versionComboBox.SelectedIndex = 0;
}
Here is a screenshot of the combo box after it's been populated:
If the user clicks the Delete button the program removes the selected item from the ComboBox using the following code:
if (versionComboBox.SelectedIndex >= 0)
{
versionComboBox.Items.Remove(versionComboBox.SelectedItem);
}
if (versionComboBox.Items.Count > 0)
{
versionComboBox.SelectedIndex = 0;
}
Here is a screenshot of the combo box after a few items have been removed:
The problem I am having is when the last item is removed the ComboBox resizes itself to the size it was when it was initially populated. There aren't any items in the ComboBox but it sizes itself as if there were.
Here is a screenshot after all the items have been removed:
As you can see the size is too big. I would think that after all the items were cleared it would look like the following:
Any ideas as to why this is happening?
Try to use this at the end of your code when you are filling the combobox items:
comboBoxNumTreno.IntegralHeight = true; // auto fit dropdown list
Then to clear it up:
comboBoxNumTreno.ResetText();
comboBoxNumTreno.Items.Clear();
comboBoxNumTreno.SelectedIndex = -1;
comboBoxNumTreno.DropDownHeight = 106; // default value
comboBoxNumTreno.IntegralHeight = false;
I know this is an old post, but it took me a long time to figure this out and I wanted to let anyone in the future know. After you clear your combo box just do a blank add items and it resets the height.
comboBox1.Items.Clear();
comboBox1.Items.Add("");
To clear your combo box you can add this:
if (versionComboBox.Items.Count == 0)
{
versionComboBox.Text = string.Empty;
versionComboBox.Items.Clear();
versionComboBox.SelectedIndex = -1;
}
Another approach is to manipulate the items in the data source and rebind the control each time (a lot less for you to worry about).
set DropDownHeight property to fix size
versionComboBox.DropDownHeight = 106; // default value
I'm trying to get the number of items in a repeater whilst handling the OnItemDataBound event. What I'm trying to achieve it quite simple; I'm trying to hide a certain label on the last item within a repeater. Currently I'm hooking into the ItemIndex and Items.Count, however as it's during the OnItemDataBound, the index and count are incrementing together.
Here's what I've got so far:
Label myLabel = e.Item.FindControl<Label>("MyLabel");
if (myLabel != null)
{
// as the item index is zero, I'll need to check against the collection minus 1?
bool isLastItem = e.item.ItemIndex < (((Repeater)sender).Items.Count - 1);
myLabel.Visible = !isLastItem;
}
I know that I could cast the DataSource to the collection of data items that were bound, however the OnItemDataBound event handler is being used across multiple repeater, so I'll need something slightly more generic.
Could you do something along the lines of, having set Visible to false by default:
if (e.Item.ItemIndex > 0)
{
var previousItem = ((Repeater)sender).Items[e.Item.ItemIndex - 1];
var previousLabel = previousItem.FindControl<Label>("MyLabel");
if (previousLabel != null)
{
previousLabel.Visible = true;
}
}
I'm not sure if this will work - I didn't know you could access repeater.Items until I saw your code - but it seems plausible.
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.
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 ;)