Web Forms :: Setting Dropdownlist Selected Value
Jan 15, 2010
My problem is I need to set selected value of a drop down list to a value I retreive from a database. The example only has a know value.
Below is the HTML and Code.
<asp:DropDownList
id="ddlCatogory1st1"
DataSourceID="srcCatogory1st1"
DataTextField="CategoryName"
DataValueField="CategoryID"
AutoPostBack="true"
Runat="server" />
<asp:sqldatasource id="srcCatogory1st1"
ConnectionString="server=(local);database=db;Trusted_Connection=true"
SelectCommand="SELECT CategoryID, CategoryName FROM Categories WHERE ParentCategoryID is null ORDER BY CategoryID"
Runat="server" ></asp:sqldatasource>
Sub Page_Load()
DISPLAY_CATEGORY()
End Sub
Sub DISPLAY_CATEGORY()
ddlCatogory1st1.DataBind()
ddlCatogory1st1.Items.FindByValue("A").Selected = True
End Sub
When I run this page I get
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Source Error:
Line 222:
Line 223: Sub DISPLAY_CATEGORY()
Line 224: ddlCatogory1st1.DataBind()
Line 225: ddlCatogory1st1.Items.FindByValue("A10").Selected = True
Line 226: End Sub
Even if I take out the databind I get the same error.
View 30 Replies
Similar Messages:
Feb 8, 2011
I have a problem in setting the selected index /value in a drop down list. The list is bound by a Linq query and I want to add an item at the top of the list and set it as the selected item.
THis is the code i am using
ListItem li = new ListItem("Select", "", true);
list.DataSource = (from ap in edc.Approvers
where ! ap.approverEmail.Equals("")
orderby ap.approverEmail
select new {ap.approverEmail}).Distinct();
list.DataTextField = "approverEmail";
list.DataValueField = "approverEmail";
list.DataBind();
list.Items.Add(li);
list.Items.FindByText("Select").Selected = true;
The listItem li is the item i want to be first in the list and also selected. Adding this before the databind just loses the item.
View 2 Replies
Feb 22, 2011
I've been all over the Internet looking for an acceptable solution to this issue, but didn't find one, so hopefully I'll have more luck here. I've got a Html.DropDownList control in my application that pulls in a set of values from the database. That works just fine. However, I want to set the selected value in code, which has never worked correctly. This is, in my opinion, one of the worst implementations of Html helpers in MVC. Here's the culprit:
[Code]....
OK, it takes in a list of statuses and gets the text/value options set without a problem, but doesn't ever render the selected value on the option with a value (ID) of "5". I've stepped through the code as it is assigning these values, and it
does set the value of that option to select = true, but the rendered html doesn't reflect this. I recall something about this helper using the Model to set its selected value, but why will it not allow the value to be explicitly set? Even better, if for some reason explicitly setting this in code isn't going to work, why allow it as viable code, and just silently fail? I'm all for this coding by convention approach MVC has taken, but when the convention is explicitly overridden in code, the code should prevail, I would think.
View 1 Replies
Sep 6, 2012
protected void DDLzone1_SelectedIndexChanged(object sender, EventArgs e)
{
BindDistrict();
}
[Code]......
here when i click on ALL item from ddlzone1 it just "ALL" item in ddldistrict
i want when i select "ALL" item from ddlzone1 in ddldistrict14 show all data from database
View 1 Replies
May 7, 2015
I have two pages manager and user both have drop downs as
Week, Months and Years.
User have to enter some data week wise for each months and Manager have to approve that.
To Approve manager select months and week from dropdown on his own page and then navigate to User page.
How does I should bind the drop down so that if manager select 1st week from it's page and goes to view link of user then in drop down of user selected value shold be the same as selected by Manager on his own page.
View 1 Replies
Jul 29, 2010
I am not trying to achieve anythign fancy but just trying to set default selected value for one of the dropdown that I am using. for that I am doing Items>selected= true for whatever item I want selected when i load the page. In my case, it is a month dropdows and I am selecting date 14 as selected default value out of all 30 values but somehow, out of the blue .NEt decides to show me 29 instead of 14. I am not sure if there is some another setting that is overwritting this value.
View 2 Replies
Nov 10, 2010
I have a master page (Site.master) with a navigation menu linked to a datasource (Master.sitemap). I have a nested master page that has another navigation menu. For any item clicked in this nested navigation menu, I want a particular menu item in the Site.master navigation menu to be selected.
Here's my Site.master menu:
[Code]....
In my Site.master.cs I have this:
[Code]....
In the nested master page, Products.master I have this:
[Code]....
In the Products.master.cs file I try to change the selected item.
[Code]....
The master navigation and products navigation menus work just fine by themselves. But when I've tried to set the selected item of the master menu in the Page_Load above, I can't seem to access it. What I've found in trying to do this is the NavigationMenu seems to be uninitialized. The menu Items list is empty. What am I missing here? Why are there no menuItems in the Master.NavigationMenu control?
View 2 Replies
Nov 15, 2010
i have a setup.aspx page where in i select the theme with buttons so if i click on a button the theme should reflect in all of my pages of project.so how can i write the code do i need to call it in each page.how can i set the initial page to do so.
View 7 Replies
Mar 31, 2010
I have a datalist that holds imagebuttons which all link to images stored in a database. When I click on any of the image buttons the datalist enlarges the chosen picture and manages to dothis as the datalist is binded by the uniqueID of the image in the database. So, when I am looking at the enlarged picture, it would be nice to be able to click 'Next' & 'Prev' link buttons to move onto the next or previous picture without having to return to the datalist in between looking at a different photo.
I have managed to set up methods for clicking on 'next' and 'prev' linkbuttons that will successfully browse back and forth between photos in the datalist but the selected index always starts at 0, i.e the first photo in the datalist. So if I'm viewing the 5th image in the list and press 'next', the first image in the list shows up. I thought just by clicking on an image button would automatically set the selected index but obviously this is not the case. I have read various threads and tutorials on the net and a lot of them point to dlIcons.SelectedIndex = e.Item.ItemIndex; I have tried to put this in the itemDataBound method for my datalist but it changes nothing. And if i try to put that line of code in other messages in the class i get error messages (I'm using Visual Web Developer C#).
its part of a final year project due in 3 weeks and by now I should be writing the report! The code I'm using is pretty huge and spread out between classes but I will include what I think might help illustrate how it all works:
<asp:DataList ID="dlIcons" runat="server" DataKeyField="AttachmentID"
OnItemDataBound="dlIcons_ItemDataBound" ItemStyle-BorderWidth="1px"
RepeatColumns="5" RepeatDirection="Horizontal" CssClass="Icons"
OnSelectedIndexChanged="dlIcons_SelectedIndexChanged">
<AlternatingItemStyle CssClass="AlternatingRowStyle" />
<ItemStyle CssClass="RowStyle" BorderWidth="1px" />
<HeaderStyle CssClass="HeadeBrStyle" />
<FooterStyle CssClass="FooterStyle" />
<SelectedItemStyle CssClass="SelectedRowStyle" />
<ItemTemplate>
<asp:Label ID="lblFilename" runat="server" Font-Size="Small"
Text='<%# Eval("Filename") %>' ></asp:Label>
<br />
<asp:LinkButton runat="server" id="btnDelete" CommandArgument="<%# Bind('AttachmentID') %>"
CommandName="DELETE" Text="Delete" OnClick="btnDelete_Click"
Font-Size="small" CssClass="btnDelete" />
<br />
<asp:ImageButton runat="server" ID="imgBtnFileType" width="120" Height="120"
ImageAlign="right" ImageUrl='<%#"http://localhost:49279/PDFViewer/GetAttachment.ashx?AttachmentID=" + Eval("AttachmentId") %>'
OnClick="imgBtnFileType_Click" BorderWidth="1PX" CssClass="imgBtnFileType"
CommandName="VIEW" CommandArgument="<%# Bind('AttachmentID') %>"/>
<br /><br />
</ItemTemplate>
</asp:DataList>
The CS file:
protected void dlIcons_ItemDataBound(object sender, DataListItemEventArgs e)
{
if ((e.Item.ItemType == ListItemType.Item) || (e.Item.ItemType == ListItemType.AlternatingItem))
{
DataRowView drv = e.Item.DataItem as DataRowView;
dlIcons.SelectedIndex = e.Item.ItemIndex;
int attachmentID = (int)drv["AttachmentID"];
string fileType = (string)drv["Type"];
ImageButton imgBtnFileType = e.Item.FindControl("imgBtnFileType") as ImageButton;
string fileName = (string)drv["FileName"];
Label lblFilename = e.Item.FindControl("lblFilename") as Label;
lblFilename.Text = fileName.Length > 12 ? fileName.Substring(0, 10) + ".." : fileName;
}
}
The next and prev link buttons onclick leads to these two methods:
public int nextPic()
{
dlIcons.Items.Equals(dlIcons.SelectedIndex++);
int nextAttach = (int)dlIcons.SelectedValue;
return nextAttach;
}
public int prevPic()
{
dlIcons.Items.Equals(dlIcons.SelectedIndex--);
int prevAttach = (int)dlIcons.SelectedValue;
return prevAttach;
}
these were void methods but i've been stuck on this for hours and have resorted to fiddling with just about everything.
View 6 Replies
Mar 8, 2010
What is wrong with this? I provided my selected indexchanged and gridview.
[Code]....
View 7 Replies
May 11, 2010
I have a ASP.Net webform with a DropDownList control. This Dropdown gets it's values from a states table in an ObjectDatasource. The Dropdown contains states spelled out.
If I try to set the drop down to:
DropDownStates.SelectdValue = "Ohio"
I get an error that the value does not exist in the dropdown even though it does exist. But if I pad the value with the correct number of spaces to the right, it works like so:
DropDownStates.SelectdValue = "Ohio "
or
DropDownStates.SelectdValue = "Michigan "
How can I either define the dropdown without trailing spaces in the value of the dropwdown or set the SelectedValue with adding trailing spaces?
View 5 Replies
Apr 30, 2010
So I have a major issue and cannot find any solution online to solve it excepting one that is singlistviews. But i am also encounting some probs with listviews since i am not sure of to use it.Anyways so my major issue is that I have drop down lists that are being populated by a sqldatasource. Users are filling out a form selecting values in the drop down list which is fine, the prob exists with editing a record. I have the dataValuefield to be the Id of the data and the selected item in the dropdownlist id is being stored in a database. So I have the data in the database that is the Id of the selected item however I cant use the dropdownlist1.selectValue ='idNo' since that only works with listitems.
How can i access the dynamic rows in a dropdownlist that is being populated by a sqldatasource and set the selected item to a particular item?Any insight is greatly welcome. Even how to use listviews
View 5 Replies
Apr 15, 2010
I am having a problem with disabling DropDownList based on the chice of 1st DropDownList, there is no post back occuring, and it is a template based web app here is the current code:
<script type="text/javascript">
$(function() { var dropDownList1 = $('#<%= ddlUserType.ClientID %>');
var dropDownList2 = $('#<%= ddlMember.ClientID %>'); dropDownList1.change(function(e) {
if ( jQuery("#ddlUserType").val() != "ETOC") dropDownList2.removeAttr('disabled'); e.preventDefault();
else
dropDownList2.removeAttr('enabled'); e.preventDefault(); }
} );
</script>
what is happening now is page is blank and if I remove the above code everything shows, where I am going wrong. here is the plain and final javascript code which worked:
<script language="javascript">
function CheckDropDownState(lstbox)
{
if (lstbox.selectedIndex == 3) { document.forms[0].ddlMember.disabled = 1; }
else { document.forms[0].ddlMember.disabled = 0; }
}
</script>
and thew .aspx code: <asp:dropdownlist id="ddlUserType" runat="server" onclick="CheckDropDownState(this);"></asp:dropdownlist>
View 2 Replies
Jan 11, 2011
what i m trying is i hav two dropdownlists inside the gridview... namely say ddonsiteoffsite and ddhours... now what i want is if the selectedtext of ddonsiteoffsite is "onsite" the ddhours should b disabled... i tried the code snippet but ... its not disabling the ddhours... can someone help me please..
<asp:TemplateColumn HeaderText=" OnSite/OffSite" >
<ItemTemplate>
<asp:DropDownList ID="ddOnsiteOffside" runat="server" onchange="ToggleOnOff(this)">
[code].....
View 2 Replies
Mar 11, 2011
I'm populating a dropdownlist in a formview with a different datasource from the formview's. I need to set the selected value according to the value in the formview's datasource but I'm having a hard time doing that.
Here's the code:
<asp:FormView ID="FormView1" runat="server" DataKeyNames="ID"
DataSourceID="SqlDataSource1">
<EditItemTemplate> [code]....
View 2 Replies
Jan 18, 2010
I have a dropdownlist used to select a directory for a gridview to show images in the directory.
I am wondering how I can include the value of the dropdownlist in the formatstring or some way to have it change.
I tried
<% "~" & cboFilePath.SelectedValue & "{0}"%>
with no luck. my dropdown containes "/images/" and "/images/uploadedPhotos/" and the gridview lists the files, but the images dont show.
View 2 Replies
Nov 25, 2010
I have officially wasted about two days trying to figure out what the heck was going on with my asp.net page. I actually thought it was an issue with my updatepanel code, but after reading another post I was able to reproduce the same results. [URL]
I just manually added the following control to the page (no code behind for the listbox) and it is nested in an ajax tabcontrainer inside an updatepanel. If you set item 20 as selected the page flickers when loading that tab. I tried the css mentioned (style="overflow:hidden") on the tabcontainer,tab panel, update panel and dropdownlist, but no luck. Crazy select item 19 no flicker, 20 (which is actually the 21st item) and it does flicker. This is driving me insane. And yes this only occurs in FireFox ( running 3.6).
View 2 Replies
Dec 17, 2012
I am having a 2 dropdown list, in the first dropdown I have 3company names,for each company I am having separate tables,every table have a empcode, if the user select the company name in the 1st dropdownlist, as per company selected the 2nd dropdownlist it will fill the list of employee codes as per the selection..
View 1 Replies
Oct 27, 2010
In our asp.net web application we load the dropdown list boxes in the page load. We than set the SelectedValue of each dropdown list box to an object from session. We have event handlers for many of the SelectedIndexChanged events of the drop down lists boxes, but these do not get executed when we set the selected value programmatically.
Someone else mentioned this is by design, and only when a user manually changes the drop down list selected index, will the event get raised.
I would think this is a common scenario of wanting the selectedindexchanged event handled when setting the selectedvalue/selectedindex/listitem's selected property, of a DropDownList. What is the suggested way to handle this? Is there a significant drawback of creating a custom control inherited from DropDownList that has the functionality of raising this event when changing the SelectedIndex or SelectedValue?
View 1 Replies
Jan 11, 2011
I'm working with a simple MultiSelectList on C#.
I just want to populate this MultiSelectList with some string values (not a pair such as <"Key", "Value"> just <"Value">) and set some selected items.
Here's my code:
IEnumerable<string> ubicaciones = new string[] { "NEGOCIOS", "TERRITORIOS",
"LOCALIDADES" };
IEnumerable<string> ubicacionesSelected = Ubicaciones.Split(',');
UbicacionesPermitidas = new MultiSelectList(ubicaciones, ubicacionesSelected);
IEnumerable<string> transacciones = new string[] { "CARGA: ACCESORIOS",
"CARGA: EQUIPOS", "ASIGNACIONES", "DESINCORPORACIONES",
"PRÉSTAMOS", "TRASLADOS", "SALIDAS" };
IEnumerable<string> transaccionesSelected = Transacciones.Split(',');
TransaccionesPermitidas = new MultiSelectList(transacciones,
transaccionesSelected);
However, is not working... (it shows all the values on the MultiSelectList but it doesn't show any item selected) what am I missing
View 1 Replies
Mar 6, 2011
Currently I'm setting the background color of the row being edited by doing the following in the edititemtemplate.
<tr id="row" runat="server" enableviewstate="true" style="background-color: #5CB8DF">
A sorting requirement changed and the client wants to have the last edited record appear at the top of the listview. So after the save, the ListView is getting updated as I am using AJAX and not taking it out of edit mode. If the record the were editing was #3 in the list, it would move up to the first row now, but the ListView is still highlighting row 3.
I am capturing a GUID in just setting it to "display:none" on the tag. So I have a unique to work with if I need to. Is there a way to accomplish this in C# code-behind?
View 1 Replies
May 5, 2010
I have a CascadingDropDown on an ASP.NET page. Now, the prompt text is "Select State". (list of states). However, on a different version of this page (ie querystring), i might want to set the selected index to "California" for example. How can i do this? The web service used by the ajax control (ie GetStates) gets invoked at the same time the jquery document.ready function is triggered (ie asynchronously).
So when i try and set the selected index in jquery, the items are not yet bound. Is there a way to attach a handler to the ajax dropdown so that i can set the selected index once the webservice call has completed, and the items are bound?
View 1 Replies
May 20, 2010
I have the following code:
[Code]....
However, the wrong option is selected, and when I view page source, it renders like this:
[Code]....
Why is this occurring?
View 3 Replies
Aug 27, 2010
I have a modalpopup control which has a gridview and search criteria. User selects a records and clicks modalpopup ok button ( which is set as modalpopup's okbutton). I have attached an event to okbutton click event. and inside this event, I am setting a label control which in on main page which called this modalpopup. I debugged code, it comes inside that event but doesnt set value. below is my event code.
protected void btnOkCustomers_Click(object sender, EventArgs e)
{
Int32 CustomerID = Convert.ToInt32(GridView2.SelectedDataKey.Value);
orders = new Orders();
DataSet CustomersDs = orders.GetCustomerById(CustomerID);
lblCustomerName.Text = "sadasdad"; // CustomersDs.Tables[0].Rows[0]["first_name"].ToString();
HyperLink2_ModalPopupExtender.Hide();
}
View 2 Replies
Apr 27, 2010
I have a CheckboxList that seems to load and do everything right, except for when I do a postback, it will not have the Item.Selected property set. I have viewstate disabled for the entire page.
I load it like so(inside Page_Load on every load):
foreach (DataRow service in d.Tables[0].Rows)
{ [code]...
and MyLabel never has any text added to it. I can verify with the debugger that it does reach the _Click's foreach loop, but no item is ever selected. What could be the cause of this?
View 1 Replies