Quick question. Its easy enough to bind a value and text to a drop down in markup, how can I do this in C#.
To bind a single column collection
_dd_City.DataSource = LNQ.tbl_cities.Select(a => a.desc);
_dd_City.DataBind();
however say I wanted to set the value to an integer value and the text to the city name, how could I do that ??
You just need to specify the name of the properties from the objects in your collection that will be used for the text and value like this:
_ddCity.DataTextField = "desc";
_ddCity.DataValueField = "Id";
_dd_City.DataSource = LNQ.tbl_cities.Select(a => new { a.Id, a.desc});
_dd_City.DataBind();
You can set the text and value field on your markup too.
<asp:DropDownList ID="_ddCity" runat="server" DataValueField="Id" DataTextField="desc">
</asp:DropDownList>
Say your City object has members called "Id" and "CityName", you would just do this before calling DataBind:
_dd_City.DataTextField = "CityName";
_dd_City.DataValueField = "Id";
_dd_City.DataValueField="value"
_dd_City.DataTextField="key"
_dd_City.DataSource = LNQ.tbl_cities.Select(a => new {value=a.desc, key=a.id});
_dd_City.DataBind();
Related
I have a dropdownlist where I want to display a list of users. To call the users I use ChatUserDetails.GetPXPUsers()
Which brings me to this code:
public static List<ChatUserDetails> GetPXPUsers()
{
List<ChatUserDetails> Users = new List<ChatUserDetails>();
string SQL = SelectPXPUsers;
DataTable dtMainItems = ChatUserDetails.CustomFill(SQL, null);
foreach (DataRow dr in dtMainItems.Rows)
{
Users.Add(new ChatUserDetails(dr));
}
return Users;
}
But how to I display this list of users in my dropdownlist?
<asp:DropDownList runat="server" ID="DropDownListPXPUsers"></asp:DropDownList>
You can bind your list to your drop down at runtime by using the following code. You will need to specify which properties of the object are to be used.
DropDownListPXPUsers.DataSource = GetPXPUsers();
DropDownListPXPUsers.DateTextField = "PropertyOne"; // name of 'ChatUserDetails' property
DropDownListPXPUsers.DataValueField = "PropertyTwo"; // name of 'ChatUserDetails' property
DropDownListPXPUsers.DataBind();
Read more: See Examples in the DropDownList documentation.
First you'll need to set the DataSource for the DropDownList and then you will need to call DataBind().
if(!IsPostBack)
{
DropDownListPXPUsers.DataSource = GetPXPUsers();
DropDownListPXPUsers.DataBind();
}
I have several controls that I am trying to bind to LINQ queries but am getting the following error:
$exception {"DataBinding: 'System.Data.DataRow' does not contain a property with the name 'Key'."} System.Exception
{System.Web.HttpException}
I'm binding it the following way:
myDropDownList.DataSource = myDataTable.AsEnumerable().Where(
r => ((string) r["ColumnName"]) == "ColumnIWant").ToList()
myDropDownList.DataTextField = "Key";
myDropDownList.DataValueField = "Value";
I have tried this both with and without the .ToList(), as suggested in other answers but with no effect.
"myDataTable" has both columns "Key" and "Value". It was my understanding you could bind this way, but I seem to be missing a step in specifying the property names.
My suggestion (as it has worked to me this way with GridView and DropDownList controls), is that you specify this DataTextField and DataValueField properties in the design file (aspx) like this:
<asp:DropDownList ID="DropDownList1" runat="server"
DataTextField="Key" DataValueField="Value">
</asp:DropDownList>
This way, you can still apply the ToList() function to the DataTable and it will work (tested).
If if doesn't, maybe you need to set up one break-point after filling up your myDataTable and another one after the LINQ query, to check if the "Key" and "Value" columns are still there.
If it defenitely contains values for key and Value in the data table then i suggest you to use like the following :
myDropDownList.DataSource = myDataTable.AsEnumerable().Where(
r => (r.Field<string>("ColumnName")) == "ColumnIWant").ToList<DataRow>();
myDropDownList.DataTextField = "Key";
myDropDownList.DataValueField = "Value";
I had changed ToList() to .ToList<DataRow>(); so that the datasourse can find the key and value as same as from a datatable, and change the comparison like this: r.Field<string>("ColumnName")
Using .CopyToDataTable() works for what I'm trying to do, but I'd still prefer to know how to bind the data directly to the EnumerableRows collection if that's possible.
Here is what I did:
myDropDownList.DataSource = myDataTable.AsEnumerable().Where(
r => ((string) r["ColumnName"]) == "ColumnIWant").CopyToDataTable();
myDropDownList.DataTextField = "Key";
myDropDownList.DataValueField = "Value";
I have set of enums bound to a dropdown list.
((DropDownList)control).DataSource = DefaultSync;
((DropDownList)control).DataBind();
Here Defaultsync is the list which contains 2 enums.
List<MyEnum> DefaultSync=(List<SyncRequestTypeEnum>)(Enum.GetValues(typeof(SyncRequestTypeEnum)).Cast<SyncRequestTypeEnum>().Except(new SyncRequestTypeEnum[] { SyncRequestTypeEnum.ProjectLevel })).ToList();
Now I wanted to get the id of the enum based on the user selection of the dropdownlist.
I used the following code but it is giving an error as the list does not contain value for it.
public int EnumID
{
get
{
return Convert.ToInt32(ddlselection.Selectedvalue);
}
set
{
ddlselection.SelectedValue = Convert.ToString(value);
}
}
Can someone help on this?
Error is :
'ddlselection has a SelectedValue which is invalid because it does not exist in the list of items.
Parameter name: value
In order to use SelectedValue property you need to specify which property of your data item is the value property and which one is the displayed text. I would suggest changing your code to something like this:
var list = control as DropDownList;
list.DataSource = Enum.GetValues(typeof(SyncRequestTypeEnum))
.Cast<SyncRequestTypeEnum>()
.Except(/*..*/)
.Select(x => new KeyValuePair<SyncRequestTypeEnum, string>(x, x.ToString())
.ToList();
list.DataValueField = "Key";
list.DataTextField = "Value";
list.DataBind();
And your property should work fine.
Another example and more detailed explanation on MSDN.
This is a Dropdown control where I am binding the data, after bind I am putting the select statement. Even though the index is kept to 0 always select comes last like this:
Current output:
india
Auz
US
--select--
Required output:
--select--
india
AUZ
US
My Code
ddlcounty.DataSource = dtNew;
ddlcounty.DataTextField = "Weight";
ddlcounty.DataValueField = "Weight";
ddlcounty.DataBind();
ddlcounty.Items.Add("--Select--");
ddlcounty.SelectedValue = "0";
What is the change required here?
Thanks
You're doing your binding first.
When you get to the part where you are adding your default condition, you're actually adding to the end of the list.
Instead of :-
ddlcounty.Items.Add("--Select--");
Do :-
ddlcounty.Items.Insert(0, new ListItem("--Select--"));
This will insert your default option as the first element of Items.
Announced edit
You won't need :-
ddlcounty.SelectedValue = 0;
.. as if you don't explicitly specify, the first item in a drop down list is automatically selected.
If, however, you want to be explicit about it, you can do the following:-
ddlcounty.Items.Insert(0, new ListItem("--Select--","0"));
ddlcounty.SelectedValue = 0;
Would you please try below way:
Just set AppendDataBoundItems to true and Insert a ListItem as selected, and 'ClearSelection' before selecting item as below.
ddlcounty.AppendDataBoundItems = true;
ddlcounty.DataSource = dtNew;
ddlcounty.DataTextField = "Weight";
ddlcounty.DataValueField = "Weight";
ddlcounty.DataBind();
ddlcounty.ClearSelection();
ddlcounty.Items.Insert(0, new ListItem { Value = "0", Text = "--Select--", Selected = true });
ddlcounty.SelectedValue = "0";
You could also declare the "select one" ListItem declaratively in your aspx page like so
<asp:DropDownList ID="ddUIC" runat="server" AppendDataBoundItems="true" Width="200px" BackColor="White" Font-Size="10px" SelectedValue='<%# Bind("Weight") %>' DataTextField="Weight" DataValueField="Weight" >
<asp:ListItem Text="Select One" Value=""></asp:ListItem>
/asp:DropDownList>
But your AppendDataBoundItems would have to be set to true
And you could still perform your databinding on the backend.
I've read that combo boxes cannot have multiple columns. Which leaves me a bit stuck since what I want to do is display one field from a table, but return the corresponding value from a second field in the same table i.e.
I'd like to show CustomerNames in the combo box, but when the user selects a name, the CustomerID field is returned instead. Whats the best work around for this?
Best way is to use ComboBoxes DisplayMember and ValueMember properties
set the ComboBox.DisplayMember to the property you want to display. Use ValueMember for property you want to return. Then you can use the ComboBox.SelectedValue to get the current/selected ValueMember
You don't need multiple columns to implement it.
class Member
{
public string Name{get;set;}
public string Address{get;set;}
public int ID{get;set;}
public string Description
{
get
{
return string.Format("{0}, {1}", Name, Address);
}
}
}
var members = new []
{
new Member(){ID = 1, Name = "John", Address = "Addr 1"},
new Member(){ID = 2, Name = "Mary", Address = "Addr 2"}
};
m_ComboBox.DataSource = members;
m_ComboBox.DisplayMember = "Description"
m_ComboBox.ValueMember = "ID";
now you can access seleceted ID
var selectedID = m_ComboBox.CelectedValue();
The value of the ComboBoxItem does not have to be the same as the Text, consider using the ID as the value.
You can achieve the desired behaviour by setting the DisplayMember and ValueMember properties of the ComboBox to "CustomerName" and "CustomerID" respectively.
Take a look at the ValueMember property. You should set this to CustomerID. After you bind to your combobox, the actual field displayed to the user will be the CustomerName, but when you want to get the value of 'CustomerName', it will return the CustomerID.
When you want to get the value of the combobox, simply reference the SelectedValue.
If you are adamant about displaying both of these in the combobox, there are some hackish ways of doing this but I would recommend reviewing your requirements again and seeing if it is absolutely necessary.
Alternatively, you can define KeyValuePair objects with your intended Ids and text fields. Feed them to the combo, since its Items property is a collection of objects. Then, for retrieval use a cast like
var x = (KeyValuePair)combo.Items[0];
and then acces then Key and Value properties of x.
You can use Tag property of ComboBoxItem to store the value.