databinding issue asp.net dropdown list - c#

Im trying to bind my drop down list, i think is beacuse my asp code on the front end is not bound somehow
aspx
<asp:Label ID="Label2" runat="server" />
<asp:DropDownList Width="150px" ID="ddLocation" runat="server"
AppendDataBoundItems="True"
DataTextField="Name"
DataValueField="Name" AutoPostBack="True" >
</asp:DropDownList>
c# code
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Label0.Text = "Specialities";
Label1.Text = "Category";
Label2.Text = "Locations";
ddSpec.Items.Insert(0, new ListItem("Select a spec", "0"));
ddCategory.Items.Insert(0, new ListItem("Select a Category", "0"));
ddLocation.Items.Insert(0, new ListItem("<Select a Location>", "0"));
populattePage();
}
}
public void populattePage()
{
getlocation();
// getCategory()
}
public static void getlocation()
{
DataClasses_DataContext dc = new DataClasses_DataContext();
List<string> locations = (
from a
in dc.Locations
select a.Name).ToList();
DropDownList ddLocation = new DropDownList();
ddLocation.DataSource = locations;
ddLocation.DataValueField = "ID";
ddLocation.DataTextField = "Name";
ddLocation.SelectedIndex = 0;
ddLocation.DataBind();
}
I now have the Error """"DataBinding: 'System.String' does not contain a property with the name 'Name'.""" the code in the """page load""" class adds items to the drop downs however when i call the get locations class I get this error, Please help thanks in advance

There are two issues here. First - if you are going to use 2 properties of the Location object, you should use this object as a data source. No point to extract separate list of strings for this:
ddLocation.DataSource = dc.Locations.ToList();
This will resolve your exception. Also this line:
DropDownList ddLocation = new DropDownList();
should not be here, just remove it. You already have your drop down initialized.
Second issue - if you want some default item to appear in the list, you should insert it after the data binding:
populattePage();
ddLocation.Items.Insert(0, new ListItem("<Select a Location>", "0"));

ListItems have the properties "Text" and "Value". So when you create one, you can only use those properties for the drop down list text/value fields. You need to change
<asp:DropDownList Width="150px" ID="ddLocation" runat="server"
AppendDataBoundItems="True"
DataTextField="Text"
DataValueField="Value" AutoPostBack="True" >
</asp:DropDownList>
A simple way to get your location would be
List<ListItem> locations = (from a in dc.Locations
select new ListItem()
{
Text = a.Name,
Value = a.Name
}).ToList();
Then append that to your list.

So the problem is the data source you're binding to is primarily string. When you set the DataValueField and DataTextField properties, it calls the reflector and asks the object its being bound to, to give it the property. Since I'm assuming the a.Name in the query is a string, it would not have a "Name" or "Id" property. A simple solution to this would be to create an ID and Name property.
This might help illustrate what I'm trying to say. (also please camel-case your function names if you plan to do C# it helps us maintenance programmers :))
public static void GetLocation()
{
DataClasses_DataContext dc = new DataClasses_DataContext();
var locations = (
from a
in dc.Locations
select new { Name = a.Name, Id = a.Id }).ToList(); // this can be Id = a.Name or whatever too
DropDownList ddLocation = new DropDownList();
ddLocation.DataSource = locations;
ddLocation.DataValueField = "ID";
ddLocation.DataTextField = "Name";
ddLocation.SelectedIndex = 0;
ddLocation.DataBind();
}
Hope that helps!

Related

C# dropdown selected item null when list of strings/objects bound to the Data source

I am trying to bind a List of string to a Dropdown.
On frontend, I am able to see the list of dropdown correctly but when I select a value and click on search, it throws a null reference exception because it seems like it is read only. This is what I tried:
<asp:DropDownList runat="server" ID="ddl" AppendDataBoundItems="True">
<asp:ListItem Value="">Please Select</asp:ListItem></asp:DropDownList>
Code behind:
List<string> items = helper.GetData(); //A method that simply returns a list of strings.
ddl.DataSource = items;
ddl.DataBind();
protected void searchClick(object sender, EventArgs e){
/*This is null and when I inspect this, I don't see any value matching
the string selected in dropdown.*/
var selectedOption = ddl.SelectedItem.Text;
}
I tried every possible solution online. I even tried converting it to a dictionary just like it has been given here.
I also tried converting it into an object assigning it a title and an ID property as given here
Thank you.
You have bind list in dropdownlist but has not append which value has to be fetched when any value got selected.
If(!isPostBack())
{
ddl.DataSource = items;
ddl.DataTextField = "Field name which hold items(Text to be shown in ddl)";
ddl.DataValueField = "ID of items(Value for items)";
ddl.DataBind();
}
If have only list and have to append in dropdown list then use bleow code.
List<string> items=helper.GetData();
for(var i=0; i < items.Count; i++)
{
ddl.Items.Add(new ListItem(i, items[i]));
//ddl.Items.Add(new ListItem(key, source)); For reference only
}
To get value you can use:
ddl.SelectedItem.Value;
ddl.SelectedItem.Text;
Having a look at this I notice 2 things:
If the first 4 lines are in your page load make sure that you wrap them in a
if(!isPostBack)
{
}
If it is not wrapped in the !isPostBack then the value will default to the first value every time a postback occurs as the ddl wil get rebound each time.
As mentioned above you are not specifying the DataTextField or DataValueField. If these arent specified you will get object types in the dropdownlist instead of values.
Also, consider using ddl.SelectedValue rather than SelectedItem.Text as this will give you the unique ID assigned to the DataValueField
Dictionary<string, string> openWith =
new Dictionary<string, string>();
insted of list you need to use following dropdown
ddl.DataSource = items;
ddl.DataTextField = "Text Which Show In DropDown";
ddl.DataValueField = "value -When Text Is Select From Dropdown";
ddl.DataBind();

Dropdown List will not populate

I'm not sure how to correct the following problem. I have dropdown list that has a object data source. Then in the code there is a method like this
void InitPageData()
{
MembershipUser user = Membership.GetUser();
DataSetTableAdapters.MemberInfoTableAdapter da = new DataSetTableAdapters.MemberInfoTableAdapter();
DataSet.MemberInfoDataTable dt = da.GetMember((Guid)user.ProviderUserKey);
if (dt.Rows.Count == 1)
{
DataSet.MemberInfoRow mr = dt[0];
//rank.Text = mr.rank;
//position.Text = mr.position;
UserName.Text = user.UserName;
...
}
This method populates form fields on the page. What I'm trying to do is to have the rank dropdown list populated from the ods but use this method above to populate the selected item of the rank dropwon list with the line rank.Text = mr.rank. In this example the the line of code that throws the error is commented out otherwise it throws this: "'rank' has a SelectedValue which is invalid because it does not exist in the list of items.
Parameter name: value".
I've chaned the code to rank.DataTextFiled = mr.rank and rank.DataValueField = mr.rankid.ToString() but this threw another error: "DataBinding: 'System.Data.DataRowView' does not contain a property with the name 'Star'." "Star" is the value of the mr.rank.
Here is what the dropdown list and the ods look like:
<asp:DropDownList runat="server" ID="rank" CssClass="txtfield" DataSourceID="ODCRanks"
DataTextField="Rank" DataValueField="ID" AppendDataBoundItems="True">
<asp:ListItem Text="--- Select a Rank ---" Value="-1" />
<asp:ObjectDataSource ID="ODCRanks" runat="server"
OldValuesParameterFormatString="original_{0}" SelectMethod="GetRanks"
TypeName="RanksTableAdapters.RankTableAdapter"></asp:ObjectDataSource>
You should try adding data columns to your data tables (with ID and Rank being the column name) so that the data can be binded to control.
The Text property sets it by value.
See http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listcontrol.text.aspx
You seem to have what will be the text associated with the value and you want to set that as the selected item. I guess this mostly because your value collection is bound to something called ID and I figure a rank of Star isn't an ID.
If Star is what will show up as something in DataTextField, use the items collection FindByText method to select it.
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listitemcollection.findbytext.aspx
Example
ListItem li = DropDownList1.Items.FindByText("one");
if (li != null) li.Selected = true;
If Star is indeed an ID, then check that the collection is fully loaded before trying to select anything in it.
try something like
rank.SelectedIndex = rank.Items.IndexOf(rank.Items.FindByText(mr.rank));

ListView containing CheckBoxList - Selected items not showing as checked

I have a ListView with an EditItemTemplate that calls a method onItemEditing.
Within my ListView I have a CheckBoxList bound using LINQ.
In my onItemEditing method, I'm trying to check certain CheckBoxes if they are present in a look up table that links users with sectors.
However, when I load the EditItemTemplate none of the CheckBoxes are checked even though I've set them as selected in the onItemEditing method.
Here's the Method:
protected void onItemEditing(object sender, ListViewEditEventArgs e)
{
ListView1.EditIndex = e.NewEditIndex;
ListView1.DataBind();
int regId = Convert.ToInt32(((Label)ListView1.Items[e.NewEditIndex].FindControl("LblRegId")).Text);
CheckBoxList cbl = (CheckBoxList) ListView1.Items[e.NewEditIndex].FindControl("chkLstSectors");
//test to see if forcing first check box to be selected works - doesn't work
cbl.Items[0].Selected = true;
SqlConnection objConn = new SqlConnection(ConfigurationManager.ConnectionStrings["DaresburyConnectionString"].ToString());
SqlCommand objCmd = new SqlCommand("select * from register_sectors where register_id= " + regId, objConn);
objConn.Open();
SqlDataReader objReader = objCmd.ExecuteReader();
if (objReader != null)
{
while (objReader.Read())
{
ListItem currentCheckBox = cbl.Items.FindByValue(objReader["sector_id"].ToString());
if (currentCheckBox != null)
{
currentCheckBox.Selected = true;
}
}
}
}
Any ideas how to get around this?
The problem was the listView was being bound again after the checkboxlist was bound.
I removed the binding and it works!
I hope I'm not too late with my answer ;)
I have a CheckBoxList in a ListView which should DataBind like the other controls. The value in the database is a calculated value from this enumeration:
public enum SiteType
{
Owner = 1,
Reseller = 2,
SubReseller = 4,
Distributor = 8
Manufacturer = 16,
Consumer = 32
}
If the value is 24 this means Distributor and Manufacturer (8 + 16).
I added a HiddenField to the EditItem in my ListView for databinding the value:
<EditItemTemplate>
<tr>
<td>
<asp:CheckBoxList ID="cblSiteTypes" runat="server" RepeatLayout="Flow"
DataSourceID="ObjectDataSource4" DataTextField="Key" DataValueField="Value" />
<asp:HiddenField ID="hfSiteTypes" runat="server" Value='<%# Bind("SiteType") %>' OnDataBinding="hfSiteTypesBnd" />
</td>
</tr>
<!-- other data... -->
</EditItemTemplate>
The CheckBoxList is filled through another DataSource, which returns a Dictionary object with the data from the enumeration. In code behind I use the OnDataBinding method of the HiddenField for the selection:
protected void hfSiteTypesBnd( object sender, EventArgs e )
{
// read the value
HiddenField hf = (HiddenField)sender;
short val = Convert.ToInt16( hf.Value );
// find the checkboxlist
CheckBoxList cblSiteTypes = (CheckBoxList)hf.Parent.FindControl( "cblSiteTypes" );
// clear the selection (may be not needed)
cblSiteTypes.ClearSelection();
// for each item
foreach ( ListItem li in cblSiteTypes.Items )
{
// get the value from each item and...
short v = Convert.ToInt16( li.Value );
// ...look up whether this value is matching or not
if ( ( val & v ) == v ) li.Selected = true;
}
}
Et voilĂ !

ASP.NET: Problem with CheckBoxList and OnSelectedIndexChanged

I'm having a problem with CheckBoxList and OnSelectedIndexChanged:
<asp:UpdatePanel runat="server">
<ContentTemplate>
<asp:CheckBoxList
id="lstWatchEType"
runat="server"
DataTextField="DescriptionText"
DataValueField="Id"
AutoPostBack="true"
OnSelectedIndexChanged="lstWatchEType_SelectedIndexChanged"/>
</ContentTemplate>
</asp:UpdatePanel>
This is populated in Page_Load (!IsPostBack)
public static void PopulateWatchEType(CheckBoxList list, Guid clientId)
{
OffertaDataContext db = new OffertaDataContext();
var ds = (from e in db.EnquiryTypes select new {
Id = e.Id,
DescriptionText = e.DescriptionText,
IsWatching = !db.WatchXrefEnquiryTypes.Any(f => f.ClientId.Equals(clientId) && f.EnquiryTypeId==e.Id && f.Inbox==false)
});
list.DataSource = ds;
list.DataBind();
foreach(var item in ds)
{
list.Items.FindByValue(item.Id.ToString()).Selected = item.IsWatching;
}
}
My problem is in:
protected void lstWatchEType_SelectedIndexChanged(Object sender, EventArgs e)
{
ListItem item = lstWatchEType.SelectedItem;
...
}
Where item is always the first element in the list???
The selected item property will return the selected item with the lowest index inside of the list. If the first item is selected, then it will return the first item.
To get the latest selected item, perhaps you can create a global variable and set that variable on index changed. You can create a ListItem collection that first holds all of the initial selected indexes like Kirtan suggested, then create a new collection that holds all of the newest selections whenever the selected index changes. Match the two lists, and whatever item is in the new list that is not in the older list is your latest selected index.
Hope this helps.

How do I load a dropdown list in ASP.NET and C#?

How do I load a dropdown list in asp.net and c#?
You can also do it declaratively:
<asp:DropDownList runat="server" ID="yourDDL">
<asp:ListItem Text="Add something" Value="theValue" />
</asp:DropDownList>
You can also data bind them:
yourDDL.DataSource = YourIEnumberableObject;
yourDDL.DataBind();
Edit: As mentioned in the comments, you can also add items programatically:
yourDDL.Items.Add(YourSelectListItem);
using Gortok's example, you can databind the list to the dropdownlist also
List<Employee> ListOfEmployees = New List<Employees>();
DropDownList DropDownList1 = new DropDownList();
DropDownList1.DataSource = ListOfEmployees ;
DropDownList1.DataTextField = "TextFieldToBeDisplayed";
DropDownList1.DataValueField = "ValueFieldForLookup";
DropDownList1.DataBind();
wow...rather quick to the point there...
DropDownLists have an items collection, you call the Add method of that collection.
DropDownList1.Items.Add( "what you are adding" );
If you have a collection of employee objects, you could add them like so:
List<Employee> ListOfEmployees = New List<Employees>();
DropDownList DropDownList1 = new DropDownList();
foreach (Employee employee in ListOfEmployees) {
DropDownList1.Items.Add(employee.Name);
}

Categories

Resources