Checkboxlist + getting id's of all the checkboxes - c#

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.

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.

Find what Elements were added by Javascript

I have got an ASP-Site, which enables the user to Add Label-Elements. I don’t know how many Labels where added or which ID they have. I know only, they will be within the Panel pnl_Added. After the user has added all his labels, he pushes a Send-Button for Update.
So, now I am at my Server, awaiting this postback, but I don’t know where, when and how to find out, which Elements were Added to pnl_Added. Can somebody help me?
I have tried something like that:
protected void Page_Load(object sender, EventArgs e)
{
[...]
for (int i = 0; i < pnl_Added.Controls.Count; i++)
{
[...]
}
[...]
}
But I think it is too late because of the loaded ViewState? Is that possible?
I am working with VS 2013, ASP c#, with the .Net Framework 4.
On server, controls tree doesn't created from actual client HTML. Actually, server doesn't know anything about client HTML besides input tags values in scope of submitted form. In general, all controls available in Page_Load method, created on server side from aspx file markup.
To implement your scenario, you need to add hidden field for each label, added from client and save label's inner text into hidden field's value. Then you'll can get these labels texts as below:
var labels = Request.Form["hiddenField's name"] as string[];
You should go one lever deeper and take the added elements from Request variable, because the control pnl_Added doesn't know about them as there was no postback.
Something like this:
Request.Form["field_id"]
I suggest to run the page in debug mode, review Request.Form collection and find what you need. You should see your label elements there.

C# SelectedValue in a Listbox

I'm adding data to my listbox using this code :
SqlCommand cmd1 = new SqlCommand("SELECT U_Naam, U_Voornaam, User_ID FROM Login ORDER BY U_Naam ASC", con);
dr = cmd1.ExecuteReader();
int teller = 0;
while (dr.Read())
{
hulp = dr["U_Naam"].ToString() + " " + dr["U_Voornaam"].ToString();
lbNiet.Items.Add(hulp);
lbNiet.Items[teller].Value = dr["User_ID"].ToString();
teller++;
}
When I run the program and select an item in the list I want to get it's value (Using selectedvalue). When I do this it allways gives a nullref (no value). I've read somewhere the selected item is lost after a postback ? How can I solve this ?
thanks !
replace these lines
lbNiet.Items.Add(hulp);
lbNiet.Items[teller].Value = dr["User_ID"].ToString();
with
lbNiet.Items.Add(new ListItem(hulp,dr["User_ID"].ToString();));
I don't think the selected item is lost after PostBack under normal circumstances - my guess is that you are accidently populating the ListBox again after PostBack so that when you make a selection, the system hits the Page_Init / Page_Load (or whatever event you choose to populate the ListBox in) and recreates all the options. Doing this would overwrite the currently selected option.
If that's the case it's easily avoided by check for PostBack first before repopulating the list.
Are you running that code in the Load of your ASP.NET page without checking to see if it is a Postback? You should make sure to wrap your loading code in a if (!IsPostback) {} block if you're doing it in the load of the page.
Databinding your data instead of adding in a loop will help.
Are you using the ViewState for your page?
If yes, check the IsPostBack property of the page, and don't populate your list after postback.
you can use Request.Form to find the posted value
or I think if you use a scriptmanager and an updatepanel it refills the box after a postback

How to add check box inside combobox in 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();
}

Making a treeview mimic required field validator functionality

I am in need of validating a TreeView to make sure that users have selected something. What I need is something that mimics a RequiredFieldValidator and stops a page from posting back with any data until something is selected.
I am using C# and ASP.NET 3.5
I have tried this and it did not work for me:
if (TreeView.SelectedNode.Value == null)
{
lblError.Text = "Required";
lblError.ForeColor = Color.Red;
}
I am at a loss, and any help would be very appreciated.
As far as I can say, TreeView is basically used for navigation and in navigation you cannot force a user to choose node. But if its requirement in your app. If your are navigating to other page, then you can do one thing, add some flag or value to your querystring so that the app will know whether its coming from treeview or directly by copy pasting the url. Catch it all in your Page_Load event.
or Create a Session variable in the treeview selected event Session["TreeviewChecked"]= true;
In your code check if Session is null or not.
I hope this will help.

Categories

Resources