Bind null value to a dropdown list - asp.net

I am using items from sharepoint list to be binded to a dropdown list. However, I want the first value in the dropdown to be empty. I cannot insert a null value in the sharepoint list item.
Please let me know how can I do it programmatically.
Below is the code I am using to bind the list to dropdownlist
if (Fldname.Contains("xxxxxx"))
{
ddllist.DataSource = data.getCode();
ddllist.DataTextField = "Title";
ddllist.DataValueField = "Alphabetic_x0020_Code";
ddllist.DataBind();
ddllist.SelectedValue = string.Empty;
ddllist.Width = 120;
}

there has to be something like this. Where 0 is the position you want the new item be - which is the first in this case. Can do this after the databinding.
ddllist.Items.Insert(0 , string.empty);

Related

Get attribute from DropdownList SelectedItem

I have a dropdownlist where I need to store more data than the standard list item allows. The approach I've taken is to add an attribute to each of the listitems.
I monitor for changes and can return the SelectedIndex, but I'm not sure how to get the attribute back from there, or whether there are any easier ways of achieving this.
Any ideas?
Try this:
ddl.SelectedItem.Attributes["key"];
I did try this once before and i figured i could not really use the attribute's on the DropDownList attributes.
What i did was the following:
Create a list containing a KeyValuePair. The Key in the KeyValuePair is the same ID as you put in your DropDownList Item.
The value of the KeyValuePair, is the value (or values) that you would like to keep/connect with your item.
You can store the List in your viewState and read the data once you have selected an item in your DropDownList and find the right KeyValuePair using the ID.
So you can "store" the data like this:
var listKeyValuePair = new List<KeyValuePair<int, string>>();
listKeyValuePair.Add(new KeyValuePair<int, string>(1, "data"));
ViewState["DataList"] = listKeyValuePair;
And you can get your data like this:
var listKeyValuePair = (List<KeyValuePair<int, string>>)ViewState["DataList"];
var dataILikeToHave = listKeyValuePair.Find(k => k.Key == Convert.ToInt16(dropDownlist.SelectedItem.Value));

replacing items in dropdownlist

I have a drop down list that is bound to some items. i want to replace the selected item with a text box value and again want to bind the dropdownlist with new values.
For this i am currently storing the dropdown list items in a temporary List. How can I replace the current selected item with textbox value.
for (int i = 0; i < DropDownEmail.Items.Count; i++)
{
if (?)
{
ObjRegistration = new ClassRegistration();
ObjRegistration.UserName = TextBoxEmail.Text;
tempEmailList.Add(ObjRegistration)
}
else{
ObjRegistration = new ClassRegistration();
ObjRegistration.UserName = DropDownEmail.Items[i].Text;
tempEmailList.Add(ObjRegistration);
}
}
Your code doesn't make much sense as it is written now, but in general, if you want to replace an item in a dropdown list you need to do something like this:
var selectedItem = tempEmailList.SelectedItem; //returns a ListItem object
selectedItem.Text=txtField.Text;
dropDownList.DataBind(); //Rebind it so you see the change.
In your case, it seems that you are binding to a custom collection of ClassRegistration but since you are doing this on code-behind, once you bind the elements to the Dropdown list for the first time, you only have a reference to the Items collection in the dropdown which are all of type ListItem.
You can, alternatively, update your underlying custom collection and rebind that to the dropdown list:
var tempEmailList= ... //get it from DB or whatever
tempEmailList.Find(x => x.ID == int.Parse(ddl.SelectedItem.Value)).UserName = txtBox.Text;
ddl.DataSource = tempEmailList;//re-assing the datasource
ddl.DataBind();//rebind

ASP.Net MVC dropdown selected value

I have been dealing with the dropdownlist which i am able to populate but if i come back to edit a record, the dropdown is not showing the selected value.....
In controller,
var datacontext = new ServicesDataContext();
var serviceToUpdate = datacontext.Mapings.First(m => m.CustomerServiceMappingID == id);
var qw = (from m in datacontext.Mapings
where id == m.CustomerServiceMappingID
select m.CustomerID).First();
ViewData["CustomerID"] = qw;
int b = Convert.ToInt32(serviceToUpdate.ServiceID);
var a = datacontext.services.Select(arg => arg.ServiceID).ToList();
ViewData["ServiceID"] = new SelectList(a,serviceToUpdate.ServiceID);
In view:
#Html.DropDownListFor(model => model.ServiceID, ViewData["ServiceID"] as SelectList)
serviceToUpdate,ServiceID has the right value but somehow when I try to edit the selected value is not returned... instead the first value of dropdown is only returned...
I had the same problem. Use the null object pattern where you have a reserved id and the display name of the item is "please choose..." or something similar. Before passing in the model to the view, append to the beginning of the collection the null object. In the controller on the way back in, test for it. You can then set the property to null if the person didn't choose anything.
Here is my question:
DropDownListFor Not Displaying/Persisting Null for First Choice in List
You shouldn't have to use view data explicitly either like you are doing.
Code in Controller:
ViewBag.Services = new SelectList(a, "ServiceId", "#Servicename");
ServiceId is the property representing the key-value for the item displayed in the dropdown list
#Servicename stands for the property representing the text you want to display for the item in the dropdownlist)
Code in View:
#using(#BeginForm){
SelectList services = Viewbag.Services;
#Html.DropDownListFor(model => model.ServiceID, services)
}

DataBind of DropDownList works, but does not show in code behind

I'm working on web pages that have an ASP DropDownList defined, and on page load the data source is bound to it through DataSource.DataBind(). When I step through the code, the drop down list does not show anything in it, but when the page actually displays, it does have items in the list. When exactly does DataBind() get applied to the control?
The problem is that some of the values returned by the SQL back end have a null Text, so nothing is displayed in the drop down list for that row. I want to just use the Value as the Text, but only if the Text is null. And when I put the code to loop through and do that right after the DataBind(), there is nothing in the drop down list at that point in the code.
Thanks!
The best option for your specific example is to do what kd7 said, and modify your query. However, if you ever need to do other modifications to the items, you can access them in the DataBound event of the DropDownList. MSDN. This event fires after the binding occurs.
You could
a) Modify your database query to exclude null values
or
b) Before you databind, iterate through the data returned and remove the undesired values.
You can just use LINQ on the data before you assign it to create a new type on the fly with the data arranged how you want. Here is a quick example:
// This simulates the data you get from the DB
List<SomeObject> lstData = new List<SomeObject>();
lstData.Add(new SomeObject() { ID = "1", Text = "One" });
lstData.Add(new SomeObject() { ID = "2", Text = "" });
lstData.Add(new SomeObject() { ID = "3", Text = "Three" });
// This will take your data and create a new version of it substituting the
// ID field into the Text field when the Text is null or empty.
yourDropDownList.DataSource = lstData.Select(i => new {
ID = i.ID,
Text = string.IsNullOrEmpty(i.Text) ? i.ID : i.Text }).ToList();
// Then just databind
yourDropDownList.DataBind();
The DropDownList would have the following items:
One
2
Three

ListView -Dynamic Controls and DataPager events

I have a listView control which is bound to an object datasource. In the ListView1_ItemDataBound event, I am generating some dynamic controls. I do this because depending on a particular column value, i might need to generate textbox, radio button, check box etc.
Some code here:
ListViewDataItem item = (ListViewDataItem)e.Item;
typez = Convert.ToInt32(DataBinder.Eval(item.DataItem,"Type").ToString());
if (typez == 1) //1 means generate radibutton
{
string[] options = DataBinder.Eval(item.DataItem, "QuestionDetail").ToString().Split(new string[] { delimiter }, StringSplitOptions.None);
questionID = Convert.ToInt32(DataBinder.Eval(item.DataItem, "Question_ID").ToString());
int optionCount = 1;
RadioButtonList rbl = new RadioButtonList();
//set ID for the radiobtnList to the questionid no.
rbl.ID = "mcq_" + questionID;
foreach (string s in options)
{
//adds the MCQ options to list item
ListItem li = new ListItem(Util.GetAlphabet(optionCount).ToUpper() + ". " + s, Util.GetAlphabet(optionCount).ToUpper(), true);
rbl.Items.Add(li);
optionCount++;
}
//PlaceHolder PlaceHolder1 = (PlaceHolder)e.Item.FindControl("PlaceHolder1");
PlaceHolder1.Controls.Add(rbl);
I have DataPager also. When I go to the next page I want to somehow capture the user response in the previous page. Otherwise, all the user response is lost. I tried using ListView1_PagePropertiesChanging event. But here I somehow do not seem to get the dynamic controls in the page.
I need to get the radio button selected value so that I can save it or put in some session variable so that when user comes back to this page he can see his previuos values.
Could someone please suggest some insight on what I am doing wrong.
Problem is that you have to create controls in OnInit, then ViewState persister can do it's job. If you do it after OnInit, in ItemDataBound, when Postback is triggered, controls doesn't exists and their's viewstate isn't deserialized.
To access values of radio buttons and get selected one, you have to look at Request.Form dictionary and find it.

Resources