Dropdownlist i binded the values but in that dropdownlist just like group means(employee,nonemployee) so that items value is empty(""), so i can use databound event split the two fileds ,that two fields i can apply the color and underline and bould and user doesnot select that fields , so pls see the below code and modify this code.
protected void ddlconsultant_DataBound(object sender, EventArgs e) { foreach (ListItem item in ((DropDownList)sender).Items) {
string r = item.Value; if (r == "") {
item.Attributes.Add("style", "color:Red;font-weight:bolder"); } }
thanks
hemanth
I'm handling this situation on the client side, using javascript, actually jQuery
jQuery(document).ready(function () {
$("[id*=ddlConsultant] option[value='']").each(function () {
$(this).attr("disabled", "true");
$(this).css("color", "Red");
$(this).css("font-weight", "bolder");
});
});
It's probably easier to do this with server-side code, in the same place where you set the colour of list items:
item.Attributes.Add("style", "color:Red;font-weight:bolder");
item.Attributes.Add("disabled", "disabled");
This will product HTML code that looks something like this:
<option style="color:Red;font-weight:bolder" disabled="disabled">item text</option>
I know this is kinda an old question, but I've just been looking for the same information, and having just found out, thought I'd add the answer here for completeness.
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);
Im new to ASP. can any body give the sample code for select all the checkbox while selecting one checkbox from the check box list.
Select All
A
B
C
once checking the select all check from the checkbox list all other items also should get selected.
First off, Please try to search internet for answers, since you are new to ASP, its better to try examples from the internet.--> Link to W3
what you can try is on click of "select all" check box, iterate through the checkbox collection list, and set the selected property to true.
Something like this
foreach (ListItem item in this.CheckBoxes.Items)
{
item.Selected = true;
}
use jquery for this purpose , use this id input#chkView for the main checkbox that will select/deselect all checkboxes and assign this class .viewPerm to all the checkboxes that you want to to check/uncheck on click of input#chkView .
<script type="text/javascript">
$(document).ready(function () {
$('input#chkView').change(function () {
if ($(this).attr('checked')) {
$('.viewPerm > input:checkbox').each(function () {
$(this).attr('checked', true);
});
}
else {
$('.viewPerm > input:checkbox').each(function () {
$(this).attr('checked', false);
});
}
});
});
take a one checkboxlist add item, add first item text as Select All ,after creating checkbox, set autopostback property to true, and handle selectedindexchanged event of checkboxlist
use following code in in the selectedindexchaged event:
if (CheckBoxList1.Items[0].Selected == true)
{
for (int i = 0; i < CheckBoxList1.Items.Count; i++)
{
CheckBoxList1.Items[i].Selected = true;
}
}
I have multiple dropdown & listbox in my webpage.
I am trying to get a list of CategoryID from a lstCatID listbox i am able to populate the listbox with category name.
If i remember correctly in first attempt my code worked fine, after that i made some change then it stated to always get the first item selected x No. of time
<asp:ListBox ID="lstCatID" runat="server" DataTextField="CategoryName"
DataValueField="CategoryID" SelectionMode="Multiple" CssClass="lstListBox">
</asp:ListBox>
protected void Button1_Click(object sender, EventArgs e)
{
string CatID = string.Empty;
foreach (ListItem li in lstCatID.Items)
{
if (li.Selected == true)
{
// Response.Write();
CatID += lstCatID.SelectedItem.Value + ",";
}
}
Response.Write(CatID);
}
I am not sure what is going wrong i checkd MSDN it show exactly the same way of doing it.
May be i am doing something wrong.
Just to add using firefox i am able to see multiple selected value have selected property.
<option value="3" selected="selected">One</option>
<option value="2">Two</option>
<option value="29" selected="selected">Three</option>
<option value="25" selected="selected">Four</option>
<option value="22" >Five</option>
My output in this case will be 3,3,3
I would appreciate help in this regard
I am not sure what is wrong with the logic i am using.
I came across a nice solution using LINQ.
This single statement works great & gets me the desired results.
string values = String.Join(", ", lstCatID.Items.Cast<ListItem>().Where(i => i.Selected).Select(i => i.Value).ToArray());
RESULT: 3,29,25
You are setting it to the same value every time:
foreach (ListItem li in lstCatID.Items)
{
if (li.Selected == true)
{
// you are always using lstCatID.SelectedItem.Value.
CatID += lstCatID.SelectedItem.Value + ",";
}
}
When you actually want the value of the item in your loop that is selected:
foreach (ListItem li in lstCatID.Items)
{
if (li.Selected == true)
{
// get the value of the item in your loop
CatID += li.Value + ",";
}
}
Try to add Page.IsPostback on your Page_Load like
protected void Page_Load(object sender, EventArgs e)
{
// Do your API code here unless you want it to occur only the first
// time the page loads, in which case put it in the IF statement below.
if (!Page.IsPostBack)
{
}
}
Code:
protected void Button1_Click(object sender, EventArgs e)
{
string CatID = string.Empty;
foreach (ListItem li in lstCatID.Items)
{
if (li.Selected )
{
// TODO: Whatever you are doing with a selected item.
}
}
Response.Write(CatID);
}
Once i was facing the same problem and i made Postback mistake.
Hope it works.
Get the selected items using linq
var selected = lstCatID.Items.Where(i => i.Selected);
Minutes later I found a solution:
If lstLocations.Items.Count > 0 Then
For i As Integer = 0 To lstLocations.Items.Count - 1
If lstLocations.Items(i).Selected Then
'insert command
Dim selectedItem As String = lstLocations.Items(i).Text
End If
Next
End If
This worked fine in my scenario
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) {
}
}