I'm using C#, Asp.Net 4.0 and Telerik and I'm trying to interact with a RadComboBox.
I'm populating it with an entity data source like this :
<RadComboBox ID="cbMyCombo" runat="server" AutoPostBack="true" CheckBoxes="true" DataSourceID="edsMySource" DataTextField="Name" DataValueField="Number">
Now, it's populated properly from the database but all my items are unchecked... I tried unsuccessfully to check them by adding the following property "CheckBoxes=true" but it's not working...
I tried to change it in the code behind like this :
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
for (int i = 0; i < cbMyCombo.Items.Count; i++)
{
cbMyCombo.Items[i].Checked = true;
}
}
}
Nice try, no cigar...
I have the feeling that I'm doing it at the wrong moment in the page life cycle but I don't know how to make it properly...
Try this
Add an OnItemDataBound event to your RadCombobox
like this
protected void RadComboBox1_ItemDataBound(object o, RadComboBoxItemEventArgs e)
{
e.Item.Checked = true;
}
There is another way to handle this scenario. If all you want is - all the items in the combo box to be checked - then you can do so on the client side too. RadControls have rich client side API support so you can play around with the control from client side itself.
I tried a samll example to illustrate this scenario. I have the following radcomboboix defined on the page:
<telerik:RadComboBox runat="server" CheckBoxes="true" OnClientLoad="clientLoadHandler"
ID="radCombo"></telerik:RadComboBox>
I have named the combobox, set the CheckBoxes to true and I have added a client side event handler OnClientLoad. In this example i am binding the data source from the server as below:
List<string> colors = new List<string>
{
"Violet",
"Indigo",
"Blue",
"Green",
"Yellow",
"Orange",
"Red"
};
radCombo.DataSource = colors;
radCombo.DataBind();
Here is the javascript function:
function clientLoadHandler(sender) {
var combo = sender;
var items = combo.get_items();
var itemCount = items.get_count()
for (var counter = 0; counter < itemCount; counter++) {
var item = items.getItem(counter);
item.set_checked(true)
}
}
As you can see, the sender parameter of the function is the combobox. I gets items out of the combobox and loop through each item and set its checked property using the set_checked(boolean) function.
hope you find this info useful. Do let me know what you think about this solution.
Lohith (Tech Evangelist, Telerik India)
Related
I have 2 comboboxes created with Ajax Toolkit. One of them has a list of systems. I wanted to fill the other combobox with a list of subsystems whenever a system is selected. I did not use DisplayMember or ValueMember and most examples are using them.
.aspx side just in case:
<ajaxToolkit:ComboBox ID="cbox1" runat="server" OnSelectedIndexChanged="cbox1_SelectedIndexChanged" />
Is this doable with what I'm trying? Is the event I used correct for the situation?(I guess not,but other events seem to be unrelated) Let me show you the code:
protected void fillSystemCombo()
{
var sysOperations = new ModelOperations.ConstantSystem.ConstantSystemOperations();
var sys = sysOperations.GetSystemList().TransactionResultList;
foreach (var item in sys)
{
cbox1.Items.Add(item.description);
}
}
This works fine and I can see the systems in my first combobox.
This is what I tried for populating the second one:
protected void cbox1_SelectedIndexChanged(object sender, EventArgs e)
{
var subSysOperations = new ModelOperations.ConstantSubSystem.ConstantSubSystemOperations();
int index = Convert.ToInt32(cbox1.SelectedItem.Value);//i think this should get the id...
var subsys = subSysOperations.GetSubSystemList().TransactionResultList;
foreach (var item in subsys)
{
if (item.sysID == index)
{
cbox2.Items.Add(item.description);
}
}
}
sysID is the foreign key in SubSystem which is the ID of System. By the way, my SelectedIndexChanged event never fired when I was debugging the program even though I clicked on an item in combobox.
I've actually found the answer after carefully reading the parameters taken by Items.Add. It wants a ListItemso if I create a ListItem inside the loop I can finally add my items with both a Text and a Value like this:
foreach (var item in sys)
{
combo1.Items.Add(new ListItem { Text = item.description, Value = item.ID.ToString() });
}
After that I can get the index with
int index = Convert.ToInt32(combo1.SelectedValue);
After a long time searching for this problem I've decided to try my luck here... I'm trying to add a tooltip (title) for the items in a Drop Down List.The title is showed in IE and Firefox browsers. The DDL is creating dynamically and the DDL's DataSource is a list called "labCourses" .This is my code:
protected void Page_Load(object sender, EventArgs e)
{
ExpScheduleClass ExpSC = new ExpScheduleClass();
List<string> labCourses = ExpSC.getCourseList();
// dynamically create a dropdown list (aka DDL)
DDLCourses = new DropDownList();
DDLCourses.DataSource = labCourses; // set the data source
DDLCourses.DataBind(); // bind the data to the DDL control
BindTooltip(DDLCourses);
DDLCourses.AutoPostBack = true;
DDLCourses.SelectedIndexChanged += DDLCourses_SelectedIndexChanged;
coursePH.Controls.Add(DDLCourses);
}
public void BindTooltip(ListControl lc)
{
for (int i = 0; i < lc.Items.Count; i++)
{
lc.Items[i].Attributes.Add("title", lc.Items[i].Text);
}
}
I looked at the option element with the web inspector and the title was there (in the html), but is does not shown when the mouse was over the option.
In other browsers the title is shown on mouse hover. What may be the cause for this? Thank you very much...
Can I not remove items from a databound listview?
I bind the list view to a collection of users. lets say the listview is displaying name/address from the test object. If I try to remove the first item as below, it still displays all the records in the collection. This does not serve any good purpose. I just want to know what am I missing.
I'm suspecting it is because the datasource is still pointing to the collection which is unchanged. but if I manually change the listview items, shouldn't it take precedence?
protected void Page_Load(object sender, EventArgs e)
{
lvTest.DataSource = new List<TestObj>{ obj1, obj2..}; //pseudo code
lvTest.DataBind();
lvTest.Items.RemoveAt(0);
}
UPDATE
I understand this is not a good way of doing this. But the purpose of this question is to know why this does not work.
I think this might be a bug in the listview control. If you check the items count in the debugger after the first item is removed, you can see that the actual count is reduced by 1, but it still renders it.
Also, if you did lvTest.Items[0].Visible = false; after the RemoveAt(0), it actually makes the second item invisible which means that listview considers the first item removed but renders it regardless.
Update 2
On request, markup and codebehind used for test are below.
<asp:ListView ID="lvTest" runat="server" >
<LayoutTemplate><asp:PlaceHolder ID="itemPlaceholder" runat="server" /></LayoutTemplate>
<ItemTemplate>
<div><%# Eval("CompanyName")%><hr /></div>
</ItemTemplate>
<EmptyDataTemplate><div>None</div></EmptyDataTemplate>
</asp:ListView>
protected void Page_Load(object sender, EventArgs e)
{
lvTest.DataSource = GetCompanyList();
lvTest.DataBind();
lvTest.Items.RemoveAt(0);
}
public static List<Company> GetCompanyList()
{
List<Company> c = new List<Company>();
Company c1 = new Company();
c1.CustomerID = "2122";
c1.ContactName = "testc1";
c1.CompanyName = "test2";
Company c2 = new Company();
c2.CustomerID = "2123";
c2.ContactName = "testc2";
c2.CompanyName = "test2";
c.Add(c1);
c.Add(c2);
return c;
}
Yes you should be able to. As I understand it, the databinding is purely a process to populate the entries on the listview, so removing them after should work.
However, if this is what you want to do, a databound list does not seem like the right answer. Either get the data first, modify it, and populate the listview with the amended list; or amend the datastream to reflect jsut what you need - which you say is not an option.
What you are saying is that you want it to be databound, but you don't have a data source that actually matches the list you require. This means it should not be databound.
Another possibility that might be interesting is to use javascript/jquery to remove the items, which migh indicate whether this is a rendering problem or an object problem.
You may have to rebind the list with:
lvTest.DataBind();
Just for kicks, try binding the ListView only on the first page load.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
lvTest.DataSource = new List<TestObj>{ obj1, obj2 ..};
lvTest.DataBind();
}
lvTest.Items.RemoveAt(0);
}
Have you tried removing it from the datasource?
List<TestObj> l = lvTest.DataSource;
l.RemoveAt(0);
I don't think you can remove the items directly from the listview - they have to be removed from the bound datasource.
Another way to populate the listbox is with a loop and add it to the items:
List<string> l = new List<string>{"A", "B", "C"};
//this.listBox1.DataSource = l;
foreach (string s in l)
{
this.listBox1.Items.Add(s);
}
You should be able to use the RemoveAt now with it.
List data = new List<TestObj>{ obj1, obj2..}; //pseudo code
lvTest.DataSource = data;
lvTest.DataBind();
// if you want to remove, remove from data source and rebind
data.RemoveAt(0)
lvTest.DataSource =data;
lvTest.DataBind();
if you remove item from list view it will remove item from list view item collection but you already data blinded to list view with fist items, until you rebind, those items will display in the list view.
But when rebinding what is happening is it take data from data source not from list view items. again it will rebind fist items because list view remove not doing any change on data source.
best way is update the data source and rebind it.
I've had problems with this type of thing. Give this a try (VB but you get it)
for i as int = lvTest.Items.count -1 to 0
lvTest.Items.RemoveAt(i)
Next
There seems to be problems when the items in the list have to "reposition" themselves.
I want that my dropdownlist display first value: "-choose car-"
I succeed at this way:
protected void ddl1_DataBound(object sender, EventArgs e)
{
Convert.ToInt32(ddl1.SelectedValue);
ddl1.Items.Insert(0, new ListItem("-Choose car-", "-Choose car-" ));
}
and that's ok,the "-choose-" is in the first place but the problem now is that if I have values,for example,the dropdownlist show like that:
-Choose car-
Subaro
Fiat
Honda
The first value that display when I'm enter to the site is the Subaro,and to see the -choose car- the user need to open the dropdownlist and then he will see the -choose car- at the first place.How can I do that from the start,from the page load - the -choose car- will display at the ddl from the page load.Where I wrong at the code ?
I tried the itemlist with AppendDataBoundItems = "true" but I got an error, and when I succeed,the problem is the same like I said before.
You were on the right track with using the AppendDataBoundItems property, it should be set to true if you're databinding the list.
Your markup should look like this
<asp:DropDownList runat="server" ID="ddl1" AppendDataBoundItems="true">
<asp:ListItem Text="-Choose car-" />
</asp:DropDownList>
and your code behind probably already looks something like this
ddl1.DataSource = [your datasource goes here];
ddl1.DataBind();
This will place the Choose car text as the first option in the drop-down list and append the rest of the options below it.
Now for the more interesting part of why you were seeing the behavior you were seeing (first item not being selected). If you look at the implementation of SelectedIndex using a tool like JustDecompile (not affiliated with Telerik, just happen to use their tool) you'll see code that looks like this:
public int SelectedIndex
{
get
{
int num = 0;
num++;
while (num < this.Items.Count)
{
if (this.Items[num].Selected)
{
return num;
}
}
return -1;
}
set
{
// stuff you don't care about
this.ClearSelection();
if (value >= 0)
{
this.Items[value].Selected = true;
}
// more stuff you don't care about
}
}
As you can see, the index isn't stored anywhere, it's computed every time based on which item has the Selected property set to true. When you set the SelectedIndex to 0 in the markup and databind your datasource, it will select the 0th item in that list, in your case Subaro. When you insert a new item at the beginning of the list, Subaro is still marked as the selected item, which is why when the page loads, you see that selected and not Choose car. If you want to mark Choose car as the selected item using code, you will have to do it after you data databind your dropdown. Please note, this is just an implementation detail of how DropdownList works. It could change in future version of ASP.NET so do not write code that relies on it working this way.
Make sure that you bind the data source and insert you "-choose care-" item first before selected he first item
make sure when you insert your 1st item "-Choose car-" you make it once not on each PostBack. Check if not IsPostBack to add the 1st item.
EDIT:
Example:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
ddl1.Items.Insert(0, new ListItem("-Choose car-", "-Choose car-" ));
}
ddl1.SelectedIndex = 0;
}
You should do ddl1.Items.Insert(0, new ListItem("-Choose car-", "-Choose car-")); first, and than ddl1.SelectedIndex = 0
private void FillCar()
{
DataTable dt = GetCar();
ddl1.Items.Clear();
ddl1.DataSource = dt;
ddl1.DataTextField = "carName"; // field name in the database
ddl1.DataValueField = "CarNum"; // field name in the database
ddl1.DataBind();
ListItem li = new ListItem();
li.Text = "--Choose car--";
li.Value = "-1";
ddl1.Items.Insert(0, li);
ddl1.SelectedIndex = 0;
}
I use method like this and call it in the page load in if (!IsPostBack){}.
(Scroll down to bottom of post to find solution.)
Got a asp.net page which contains a
Datalist. Inside this datalist, there
is a template containing a
dropdownlist and each time the
datalist is filled with an item, a
ItemCreatedCommand is called. The
itemCreatedCommand is responsible for
databinding the dropdownlist.
I think the problem lies here, that
I'm using ItemCreatedCommand to
populate it - but the strange things
is that if I choose the color "green",
the page will autopostback, and I will
see that the dropdown is still on the
color green, but when trying to use
it's SelectedIndex, I always get 0...
protected void DataListProducts_ItemCreatedCommand(object
source, DataListItemEventArgs e)
var itemId = (String)DataListProducts.DataKeys[e.Item.ItemIndex];
var item = itemBLL.GetFullItem(itemId);
var DropDownListColor = (DropDownList)e.Item.FindControl("DropDownListColor");
//Also tried with :
//if(!isPostBack) {
DropDownListColor.DataSource = item.ColorList;
DropDownList.Color.Databind();
// } End !isPostBack)
Label1.test = DropDownListColor.SelectedIndex.toString();
// <- THIS IS ALWAYS 0! *grr*
I've narrowed down the code a bit for
viewing, but still you can see what
I'm trying to do :) The reason for
why I'm doing this, and not declaring
the datasource for the colors directly
i aspx-page, is that I need to run a
test if(showColors), but I do not want
to clutter up the html-page with code
that I feel should be in the code
behind-file.
EDIT: After trying to alter
SelectedIndexChange - I'm having a
"logical" confusion in my head now -
how am I to alter elements inside the
datalist? Since, as far as I know - I
do not have any way to check which of
the items in the datalist this
particular dropdownlist belongs to...
Or? I'm going to try out a few ways
and see what I end up with ;) But do
please post your thoughts on this
question :)
SOLUTION:
Either bubble the event to ItemCommand, or Handle the event, get the senders parent(which is a datalistItem and manipulate elements in there.
protected void DropDownListColor_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList dropDownListColor = (DropDownList)sender;
DataListItem dataListItem = (DataListItem)dropDownListColor.Parent;
var item = items[dataListItem.ItemIndex];
var color = item.ItemColor[dropDownListColor.SelectedIndex];
var LabelPrice = (Label)dataListItem.FindControl("LabelPrice");
LabelPrice.Text = color.Price;
}
When the DataList is data-bound, the AutoPostBack has not been handled yet, i.e. the values in the ItemCreated event are still the original values.
You need to handle the SelectedIndexChange event of the dropdown control.
Regarding your 2nd question:
I suggest you remove the AutoPostBack from the dropdown, add an "Update" button, and update the data in the button Click event.
The button can hold Command and CommandArgument values, so it's easy to associate with a database record.
some MSDN links with C# examples on bubbling
http://msdn.microsoft.com/en-us/library/system.web.ui.control.onbubbleevent.aspx
http://msdn.microsoft.com/en-us/library/aa719644(VS.71).aspx
http://msdn.microsoft.com/en-us/library/aa720044(VS.71).aspx
Thank You for your solution
protected void ddlOnSelectedIndexChanged(object sender, EventArgs e) {
try {
ModalPopupExtender1.Show();
if (ViewState["Colors"] != null) {
FillColors(ViewState["Colors"].ToString());
}
DropDownList dropDownListColor = (DropDownList)sender;
DataListItem dataListItem = (DataListItem)dropDownListColor.Parent;
Image image = (Image)dataListItem.FindControl("mdlImage");
Label ProductCode = (Label)dataListItem.FindControl("lblprdCode");
Label ProductName = (Label)dataListItem.FindControl("lblProdName");
DropDownList ddlQuantity = (DropDownList)dataListItem.FindControl("ddlQuantity");
Label ProductPrice = (Label)dataListItem.FindControl("lblProdPrice");
Label TotalPrice = (Label)dataListItem.FindControl("lblTotPrice");
//Label ProductPrice = (Label)dataListItem.FindControl("lblProdPrice");
} catch (Exception ex) {
}
}