How to add check box inside combobox in c# - c#

I want to add check box inside comboBox in C#. My purpose is that the user can select multiple values from one ComboBox ( Check all and Uncheck all ).
Please Help

You have to extend the ComboBox control by providing your own rendering strategy, and "manually" adding a CheckBox.
Theses open source project are ready to use :
http://www.codeproject.com/KB/combobox/CheckComboBox.aspx
http://www.codeproject.com/KB/combobox/extending_combobox.aspx

It is a wrong usage of a ComboBox control, because the user has no possibility to see his choices. For multiple selection, I recommend you to consider this CheckedListBox control:
link to MSDN

There is an ASP.NET open source control at http://dropdowncheckboxes.codeplex.com/ that I've used and been very happy with. There is also a WinForms open source control at http://www.codeproject.com/KB/combobox/extending_combobox.aspx that doesn't look quite as strong but maybe somebody could combine the best of both. If well implemented this is really a great addition to your toolkit. The above 2 implementations show all of the items selected and give you a number of related checkboxes in a reduced area and with excellent grouping. My addition to the ASP.NET version was to allow a list of checked files to use just file names instead of full paths if this gets too long. See above link for full code. Below is just my addition which is called instead of UpdateSelection in your postback handler:
// Update the caption assuming that the items are files
// If the caption is too long, eliminate paths from file names
public void UpdateSelectionFiles(int maxChars) {
StringBuilder full = new StringBuilder();
StringBuilder shorter = new StringBuilder();
foreach (ListItem item in Items) {
if (item.Selected) {
full.AppendFormat("{0}; ", item.Text);
shorter.AppendFormat("{0}; ", new FileInfo(item.Text).Name);
}
}
if (full.Length == 0) Texts.SelectBoxCaption = "Select...";
else if (full.Length <= maxChars) Texts.SelectBoxCaption = full.ToString();
else Texts.SelectBoxCaption = shorter.ToString();
}

Related

Possible to have dynamic content with accessable controls in asp.net/C#

I really hope that someone can help, pointing me in the right direction. I'm still new to the more advanced features of asp.net / C#.
What i need is a div, in that div i would want some informations from the database. furthermore i want a textbox with a number and an arrow up and down to increase/decrease the amount in the textbox. And at last a button outside the div to submit the value.
Now the tricky part (for me), is that one div is not enough, I need one div for each "person" in the database. i can easily make that, but.. if i add it dynamically from the .aspx.cs file i am not able to access the value like : textbox1.text; because textbox1 does not exist in the code before it is created.
I have looked at listview and a repeater, but those seems more like they're for making lists, and i need more than that, as i need some functionally too.
The way i would do it now is to add the div by innerhtml. and then adjust the amount by a for loop which also inserts the information from the database which i got in an array. But as said, that doesn't really do the trick when i need to access the textbox and stuff.
Thanks in advance for just looking at it.
EDIT:
I'm not looking for at complete solution, i just want some directions.
I will asume by your post description that by asp.net you mean webForms. If you're new on asp.net development, you have to know that there are different development, in the past (but still very commonly used) you would use WebForms, now at days the trends are using asp.net MVC framework.
now back to your question:
in asp.net WebForms, you have your code defined in two sides: your markup (HTML code normally in a .aspx file) and your code-behind (c# or vb code normally in a .aspx.cs or .aspx.vb).
what I would suggest you to do, is to add your logic for retrieving data from your database in your page_load() function of your code-behind, with this data you would normally use a loop to read all your results and for each result you would create your div with your textbox inside (the trick is using native .net framework classes instead of inserting the HTML directly). a simple example:
protected void Page_Load(object sender, EventArgs e)
{
string[] personsIDs; //<-- this came from your database
Dictionary<string, TextBox> textBoxes = new Dictionary<string, TextBox>();
foreach(string personID in personsIDs)
{
TextBox personTextBox = new TextBox();
personTextBox.ID = "textBox"+personID;
textBoxes.add("textbox"+personID, personTextBox);
}
I explain you:
first, I'm assuming there is an array of the personsIDs, so I created a dictionary (key -> value object) using strings as keys and TextBoxes as values.
then using a foreach I read all the personsID's, and for each one of them I create a new TextBox UIControl and add it to the dictionary using the personID as key. I also added its ID property as "textbox"+PersonID.
this way you can access your textboxes from code-behind by using your dictionary:
textBoxes["textbox"+personID] //(e.g: textBoxes['textBox11'])
but also, since your textBox.ID is equal to textbox+personID, you can also reference it after page has been rendered (e.g. using javascript).
now to add this controlers to your page, just use a container(UIControl) that already exists on your page, and use
container.controls.add(textbox);
this process can be expanded for extra elements, for instance:
1.- have a main placeholder already defined in your page:
<asp:Panel ID= "Panel1" runat = "server">
2.- in your code-behind for each person create a new panel and add all the elements you want inside that panel:
//this goes inside your foreach
Panel innerPanel = new Panel();
TextBox textBox = new TextBox();
Label label = new Label();
innerPanel.controls.add(textbox);
innerPanel.controls.add(label);
////
finally add your innerPanels in to your main panel:
panel1.controls.add(innerPanel);
so there you go, that's basically the idea, hope this helps.

TextDecorations Error in C# and ASP.NET

Hi & thanks in advance,
New to the Visual C# and ASP route and trying to create a shopping list: add, removing (either all or one at a time), works but I've come undone with the text decoration depending on a check box.
I'm trying to add some text decorations to the checkboxlist items' text depending on condition, in this case, whether or not a check box is 'checked'.
Below is my code, however I'm getting an error where the TextDecorations has no definition.
According to MSDN it comes from the System.Windows namespace, which is defined at the top of my code.
Any suggestions or help would be greatly appreciated.
Below is my function which I am trying to get to run through all of the list items and if the checkbox is checked then strikethrough the text,
protected void Finished_Click(object sender, EventArgs e)
{
foreach(ListItem li in TaskList.Items)
{
if(li.Selected)
{
li.TextDecorations = TextDecorations.Strikethrough;
}
}
}
Define css styles as per example and then set required class to the li-item
if(li.Selected)
{
li.CssClass = "dupa";
}
More here Striking through a number in an ordered list CSS/HTML

Temporarily change a Sitecore item's layout

Using this code I managed to change the renderings on the current item. However this changed it permenantly in Sitecore (the changes were could be seen in the CMS) and not temporarily, as I expected.
void ReplaceLayout(Item item)
{
if (item == null)
return;
using (new SecurityDisabler())
{
// New item
LayoutField newLayoutField = new LayoutField(item.Fields[Sitecore.FieldIDs.LayoutField]);
LayoutDefinition newLayoutDefinition = LayoutDefinition.Parse(newLayoutField.Value);
DeviceDefinition newDeviceDefinition = newLayoutDefinition.GetDevice(Sitecore.Context.Device.ID.ToString());
// Current item
LayoutField layoutField = new LayoutField(Sitecore.Context.Item.Fields[Sitecore.FieldIDs.LayoutField]);
LayoutDefinition layoutDefinition = LayoutDefinition.Parse(layoutField.Value);
DeviceDefinition deviceDefinition = layoutDefinition.GetDevice(Sitecore.Context.Device.ID.ToString());
deviceDefinition.Layout = newDeviceDefinition.Layout;
deviceDefinition.Renderings = newDeviceDefinition.Renderings;
Sitecore.Context.Item.Editing.BeginEdit();
layoutField.Value = layoutDefinition.ToXml();
Sitecore.Context.Item.Editing.EndEdit();
}
}
I don't want to make permenant changes to the item, I just want to replace the currently displayed items renderings on the fly if some conditions are met. Does anyone know how to alter an item's layout in this way?
You explained in your comments that you want to display certain sublayouts in the sidebar depending on certain form parts/steps.
You can do that by adding a PlaceHolder that will fit the sublayouts (e.g. in your sidebar) and use this code to dynamically render sublayouts to it.
First you need an item (i call it a snippet item) that has the sublayout configured on its presentation settings.
Then you can use code to render that item inside the placeholder (phSideBarPlaceHolder).
// Load snippet item
Item snippet = Sitecore.Context.Database.GetItem("{id-or-path-of-snippet-item}");
// Get the first rendering from item's presentation definition
RenderingReference rendering = snippet.Visualization.GetRenderings(Sitecore.Context.Device, false).FirstOrDefault();
// We assume that its a Sublayout, but you can also check for xslt and create an XslFile() object
Sublayout sublayout = new Sublayout();
sublayout.DataSource = snippet.Paths.FullPath; // creates a reference to the snippet item, so you can pull data from that later on
sublayout.Path = rendering.RenderingItem.InnerItem["Path"];
sublayout.Cacheable = rendering.RenderingItem.Caching.Cacheable;
// Copy cache settings
if (rendering.RenderingItem.Caching.Cacheable)
{
sublayout.VaryByData = rendering.RenderingItem.Caching.VaryByData;
sublayout.VaryByDevice = rendering.RenderingItem.Caching.VaryByDevice;
sublayout.VaryByLogin = rendering.RenderingItem.Caching.VaryByLogin;
sublayout.VaryByParm = rendering.RenderingItem.Caching.VaryByParm;
sublayout.VaryByQueryString = rendering.RenderingItem.Caching.VaryByQueryString;
sublayout.VaryByUser = rendering.RenderingItem.Caching.VaryByUser;
}
// Now render the sublayout to the placeholder
phSideBarPlaceHolder.Controls.Add(sublayout);
If you need more info about how to read data the DataSource property inside the sublayout code, Mark Ursino has written an article about that: http://firebreaksice.com/using-the-datasource-field-with-sitecore-sublayouts
Sitecore constructs the rendering controls and inserts them into the page very early in the ASP.NET Webforms lifecycle. It's not likely you can easily do this on the layout itself. However, if you can evaluate your conditions outside the page (e.g. by examining the item itself), you can probably do this in the insertRenderings pipeline.
Use ILSpy or another decompiler to check out Sitecore.Pipelines.InsertRenderings and Sitecore.Pipelines.InsertRenderings.Processors. As with other pipelines, the order of execution of these processors is defined in Web.config. You will want to add a new processor after AddRenderings which evaluates your conditions (likely examining args.ContextItem) and then modifies args.Renderings as needed.
In your previous question you were just looking to remove sublayouts. That should be fairly easy here. Adding different sublayouts is more difficult since you would need to construct a RenderingReference. This may require that you actually create the XML definition needed for its constructor. Or, if you have another item that defines the desired new layout, consider just changing args.ContextItem earlier in the pipeline.
Rather than change sitecore presentation, can you not place the 'form' control and sidebar within one parent control container? You would then have an an easy id for a sidebar container with which to conditionally populate controls programatically from the form control.
Alternatively, could you add all the possible controls to the sidebar and 'activate' (or perhaps just make visible) the required control(s), maybe via session state variables? (I dont know if this falls foul of some lifecycle or timing limitiation)
Or you can simply use conditional rendering rules to display the renderings/sublayouts you want based on whatever logic you can dream up.

find controls that have been selected in asp.net

Hi I'm building a web application for a client with some unique controls and criteria. One page involves a detailed search function consisting of about 100 combo boxes and listboxes. What I am trying to do is do a foreach(control that has been changed/selected){} and feed it into a function to generate a query. There are 100 but the user may only use three for a particular search ?
I know there must be a way to do this. Thanks in advance for the help
Well you can use something like:
List<Control> list = new List<Control>();
public void ControlRecursive(Control Root)
{
if(typeof(ComboBox) == Root.GetType() && ((ComboBox)Root).Checked)
list.Add(Root);
else if (Root is RadListBox)
{
// deal with RadListBox here
}
// if all your other types
// ...
foreach (Control Ctl in Root.Controls)
ControlRecursive(Ctl);
}
Then call this with ControlRecursive(form1);
You could have a javascript function associated with onchange / select for each of your controls and then add to a javascript array the item that has been selected. Then you can pass that array to your query generation to know what variables to pick up for your search.

Checkboxlist + getting id's of all the checkboxes

How do I get the id's of all the checkboxes generated by a checkboxlist, with datatable as its data source?
I think I have to use the "OnDataBinding" event of the checkbox list, but I don't see how that will help me.
I am using C#
I don't think getting the id's of all the check boxes generated by the check box list is possible, so I think going the moo tools way is the right thing to do.
Any ideas?
Thanks
Ideally you would want to just attach the click event handlers to all your checkbox lists in the domReady event and this will create a much simpler function with MooTools. However, you can keep your code as-is if you prefer and just make your 2 functions a little simpler.
function ToggleSelection(ctrl, sender) {
var checkboxes = $(ctrl).getElements('input[type=checkbox]');
checkboxes.set('checked', sender.checked);
}
function ToggleSelectAll(ctrl, sender) {
var fAllChecked = ($(sender).getElements('input:checked').length == $(sender).getElements('input[type=checkbox]').length)
$(ctrl).set('checked', fAllChecked);
}
You can set the properties of your entire ELements array at once, you don't need to loop through them. In the 2nd function, I'm checking the number of elements that are checked against the total number of checkboxes and if they match that means they are all checked.
Are you using VB or C#..please tag accordingly
You can have List or string called strchklist
VB.NET
For Each li In CheckBoxList1.Items
If li.Selected Then
strchklist += li.Id
End If
Next
C#
foreach (ListItem li in CheckBoxList1.Items){
If li.Selected
strchklist += li.Id ;}
The <asp:ListItem> is not really a Control itself therefore has no ID. If you want to access it in client script add a new attribute you can reference. (yes, during OnDataBinding) Remember that these are not persisted in the ViewState however!
What exactly are you trying to accomplish? May help to elaborate somewhat.
Completely different answer...
The CheckBoxList is a bit of an odd duck... unlike other controls, it does not really have a logical mapping to an obvious HTML construct. It actually renders multiple checkboxes with derivative IDs. Those IDs seem to be generated as CheckBoxList.ClientID + "_" + ItemIndex.
You can verify this by looking at the page source. Internally, it seems the ID of the individual checkbox control is just its index, and then it's rendered with the CheckBoxList as its NamingContainer. You can use Reflector is see how the CheckBoxList control renders the output.
Still a good spot for jQuery. Just easier now you know the IDs.
I woke up this morning and thought of doing this (cblUSEquities is a checkbox list)
cblUSEquities.Attributes.Add("onclick", "javascript:alert('Clicked');");
This adds the alert to the table that the checkbox list generates. One thing to note is, the alert shows up twice If I click the text of the checkbox and once if I click the checkbox. I think this solution will work for me.
BTW, I never thought that the above code would work...
P.S Answering my own question because I wanted to write some code, which I cannot do using the comment box.
In the spirit of StackOverFlow, I arrived to something which works in my scenario but the description of the question is different? What do I do? Edit the question and mark this as answer?
I was able to do this by using mootools and this is the code.
function ToggleSelection(ctrl, sender)
{
var cblCtrl = $(ctrl);
var Allcbs = cblCtrl.getElements('input');
for(var i=0; i<Allcbs.length; i++)
Allcbs[i].checked = sender.checked;
}
function ToggleSelectAll(ctrl, sender)
{
var AllTrueCount = 0;
var cblCtrl = $(ctrl);
var Allcbs = sender.getElements('input');
for(var i=0; i<Allcbs.length; i++)
if(Allcbs[i].checked)
AllTrueCount++;
if(AllTrueCount == Allcbs.length)
cblCtrl.checked = true;
else
cblCtrl.checked = false;
}
C# code which calls the javascript functions
//Binding event to the checkbox list
cblUSEquities.Attributes.Add("onclick", string.Format("javascript:ToggleSelectAll('{0}', this);", chkAllUSEquities.ClientID));
//binding event to the select all checkbox
chkAllUSEquities.Attributes.Add("onclick", string.Format("javascript:ToggleSelection('{0}', this);", cblUSEquities.ClientID));
As it turns out I did not need to know the id's of all the checkboxes generated by the checkbox list. I was able to add the onclick javascript to those checkboxes by this line
cblUSEquities.Attributes.Add("onclick", string.Format("javascript:ToggleSelectAll('{0}', this);", chkAllUSEquities.ClientID));
Which will add the onclick event to the table that the checkbox list generates.

Categories

Resources