Combines two fields in asp.net dropdownlist - asp.net

I need to make a dropdownlist combining two fields from an xml file...
XML file:
<?xml version="1.0" encoding="utf-8" ?>
<exchangeRates>
<rate country="aud" >0.97</rate>
<rate country="usd" >1.01</rate>
</exchangeRates>
I need for the dropdownlist to show country and the rate like
aud 0.97
usd 1.01
Something like
SELECT country + rate AS NewColumn FROM XML above
And then use NewColumn for the DataValueFIeld:
<asp:DropDownList ID="DropDownList1" runat="server"
DataSourceID="SqlDBSrc" DataTextField="NAME" DataValueField="NewColumn"
>
<asp:XmlDataSource ID="ListItems" runat="server" DataFile="~/ExchangeRates.xml">
</asp:XmlDataSource>
How do I do this correctly in asp.net?

You could probably use LINQ to XML.
Something like (not tested)
dim selectList = (from x in xmldoc
select new SelectListItem { Text = x.Attribute("country") + ' '+ x.Value, Value = x.Id });

You could ad a pre-render event to the control and modify the control there
<asp:DropDownList ID="DropDownList1" runat="server" onprerender="DropDownList1_PreRender"
DataSourceID="SqlDBSrc" DataTextField="Country" DataValueField="Value"
>
Note: adjust the DataText and DataValue Fields to populate the unmodified data.
In your code behind, this modifies the :
protected void DropDownList1_PreRender(object sender, EventArgs e)
{
foreach (ListItem item in DropDownList1.Items)
{
item.Text = item.Text + " " + item.Value;
}
}
This is one way to do it but there may be other better ways before binding the list.

<asp:DropDownList ID="DropDownList9" runat="server"
DataSourceID="SqlDataSource3" DataTextField="**CALL_NAMESURNAME**"
DataValueField="CALL_NAME">
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource3" runat="server"
ConnectionString="<%$ ConnectionStrings:McCarthyConnectionString %>"
SelectCommand="SELECT [CALL_NAME], [SURNAME],**CALL_NAME + SURNAME AS [CALL_NAMESURNAME]** FROM [Sheet1$] where COY_NAME LIKE '%abc%'">
</asp:SqlDataSource>
Check the ** ** parts.

Related

Replace SqlDataSource with EntityDataSource

I have a DataGrid (destination) with a countryID column, this is binded to a DropDownList to view the countries. I have countries and countryGroups tables too, where countries.countryGroupId = countryGroups.countryGroupId. The list have to be formatted therefore I use SqlDataSource to get the formatted list:
SELECT c.countryID, cg.countryGroupName+': '+c.CountryName as Name
FROM countries AS c INNER JOIN
countries_groups AS cg ON c.countryGroupID = cg.countryGroupID
ORDER BY cg.Sort, c.CountryName
here's the dropdownlist originally binded to sqldatasource:
<asp:DropDownList ID="ddlCountryID" runat="server" Width="160px" DataSourceID="dsCountries"
AppendDataBoundItems="true" DataTextField="Name" DataValueField="countryID"
SelectedValue='<%# Bind("countryID") %>'>
<asp:ListItem Value="" Text="Select"></asp:ListItem>
</asp:DropDownList>
I would like to replace the SqlDataSource to EntityDataSource for the country field. I created the following ProductionModel
VS2010 has been created the public partial class ProductionEntities : ObjectContext...
I created an EntityDataSource:
<asp:EntityDataSource ID="EntityDataSource1" runat="server"
ConnectionString="name=ProductionEntities"
DefaultContainerName="ProductionEntities" EntitySetName="countries"
Include=""
onquerycreated="EntityDataSource1_QueryCreated"
ContextTypeName="ASPWebApp.Datasource.ProductionEntities">
My question is, what other steps are needed to finalyze the binding with EntityDataSource?
Thanks in advance!
UPDATE:
The solution became to be as follows (thanks to #Gaurav Jain)
protected void ddlCountryID_OnInit(object sender, EventArgs e) {
DropDownList ddlCountryID = sender as DropDownList;
ddlCountryID.DataSource = (from c in db.suppliers_countries
join cg in db.suppliers_countries_groups on c.countryGroupID equals cg.countryGroupID
orderby cg.Sort, c.CountryName
select new {
c.countryID,
Name = cg.countryGroupName + ": " + c.CountryName
});
}
and dropdownlist became to be:
<asp:DropDownList ID="ddlCountryID" runat="server" Width="160px" AppendDataBoundItems="true"
SelectedValue='<%# Bind("countryID") %>' **OnInit="ddlCountryID_OnInit"**
DataTextField="Name" DataValueField="countryID">
<asp:ListItem Value="" Text="Select"></asp:ListItem>
</asp:DropDownList>
you can use this query.
ProductionEntities db = new ProductionEntities();
ddlCountryID.DataSource = (from c in db.countries
join cg in db.countries_groups on c.countryGroupID
equals cg.countryGroupID
select new
{ c.countryID,
Name = cg.countryGroupName + " " + c.CountryName,cg.Sort})
.OrderBy(w => new {w.countryID,w.sort });
ddlCountryID.DataTextField = "Name";
ddlCountryID.DataValueField = "countryID";
ddlCountryID.DataBind();

Display more columns from the db in the DropDownList

How can I display two columns in the DropDownList in asp.net?
SqlDataSourceNamePeop.SelectCommand = "select name,forename from people";
DropDownListCaptain.DataTextField = "name";
Like this it displays only the names. But how can i display the names+forenames?
<asp:DropDownList ID="DropDownListPeople"
runat="server"
DataSourceID="SqlDataSourceNamePeop">
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSourceNamePeop"
ConnectionString="xxxxx"
runat="server">
</asp:SqlDataSource>
The easiest way is to make your sql query like this:
SqlDataSourceNameJuc.SelectCommand = "select name + ' ' +forename as FullName from people";
then bind this custom property to your drop down list like this:
DropDownListCaptain.DataTextField = "FullName";
Let me know if it fixed your problem, thanks.
Change your select command to
"Select name + ',' + forename as 'name' from people"
<asp:DropDownList ID="DropDownList9" runat="server"
DataSourceID="SqlDataSource3" DataTextField="**CALL_NAMESURNAME**"
DataValueField="CALL_NAME">
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource3" runat="server"
ConnectionString="<%$ ConnectionStrings:McCarthyConnectionString %>"
SelectCommand="SELECT [CALL_NAME], [SURNAME],**CALL_NAME + SURNAME AS [CALL_NAMESURNAME]** FROM [Sheet1$] where COY_NAME LIKE '%abc%'">
</asp:SqlDataSource>
CHECK THE ** ** PARTS
IList<PM_ClientInformation> objPM_ClientInformation = new List<PM_ClientInformation>();
//get information in objPM_ClientInformation
foreach (PM_ClientInformation f in objPM_ClientInformation)
{
string text = string.Format("{0}{1}",
f.PM_cliFirstName.PadRight(10,'\u00A0'),
f.PM_cliLastName.PadRight(10,'\u00A0'));
ddlClientName.Items.Add(new ListItem (text ,f.PM_cliId.ToString()));
}
it defiantly work.
Dropdownlist cannot display two items. you have to merge trhem and then bind the result to it.
note that there are some other dropdownlist (ajax based or simple ) which are able to bind to two or more columns, but ASP.net is not able to cope with it

asp.net dropdownlist

I have two dropdownlists for a search, the 1st list is for the city and the second is for the area within the selected city. I would like to add a default value in the 2nd dropdownlist that will search ALL of the areas by default unless a specific area is selected from the list that contains the areaID for a specific search.
<asp:DropDownList ID="DropDownList1" runat="server"
DataSourceID="SqlDataSource1" DataTextField="cityName" AutoPostBack="true" DataValueField="cityID">
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT * FROM [Cities]"></asp:SqlDataSource>
<asp:DropDownList ID="DropArea" runat="server" DataSourceID="SqlArea"
DataTextField="areaName" DataValueField="areaID">
</asp:DropDownList>
<asp:SqlDataSource ID="SqlArea" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT * FROM [area] WHERE ([cityID] = #cityID)">
<SelectParameters>
<asp:ControlParameter ControlID="DropDownList1" DefaultValue="0" Name="cityID"
PropertyName="SelectedValue" Type="Int16" />
</SelectParameters>
</asp:SqlDataSource>
<asp:Button ID="Button1" runat="server" Text="Search" onclick="Button1_Click" />
Bind the second from code behind. Create a data table and insert the Select text at the begining and bind the datatable to the DDL.
DataTable dt =
DataRow dr = dt.NewRow()
dr["areaName"] = "All";
dr["SqlArea"] = "All";
tbldata.Rows.InsertAt(dr,0);
DropArea.DataSource = dt;
DropArea.DataBind();
You can try to add for second dropdownlist OnDataBound="DropArea_DataBound" event.
And use in code:
protected void DropArea_DataBound(object sender, EventArgs e)
{
DropArea.Items.Insert(0, new ListItem() {Value = "-1", Text = "ALL"});
}
And then when you handle click event, check:
var value = DropArea.SelectedItem.Value;
if(string.equals(value, '-1')
{
use your logic here
}
Hope it will help with your problem.
Best regards, Dima.
Chris,
I got the idea below from an answer HERE, but basically you want to modify your query to be in the form of the following:
Your Original:
SELECT * FROM [Cities]
Change To:
SELECT City FROM [Cities]
UNION ALL
SELECT 'ALL'
Old question, but you never found an answer.

asp.net dropdownlist - add blank line before db values

On my page I have a DropDownList which I populate with database values from an SqlDataSource (see code below).
How can I add my own text or a blank line before the values?
<asp:DropDownList ID="drpClient" runat="server" Width="200px"
AutoPostBack="True" DataSourceID="dsClients" DataTextField="name"
DataValueField="client_id">
</asp:DropDownList>
<asp:SqlDataSource ID="dsClients" runat="server"
ConnectionString="my_connection_string"
ProviderName="System.Data.SqlClient"
SelectCommand="SELECT [client_id], [name] FROM [clients]">
</asp:SqlDataSource>
Thanks.
P.S. Do you recommend using a SqlDataSource or is it better to populate another way?
You can simply add a ListItem inside the DropDownList Markup. All the values from the DataSource will be appended after that.
<asp:DropDownList ID="drpClient" runat="server" Width="200px"
AutoPostBack="True" DataSourceID="dsClients" DataTextField="name"
DataValueField="client_id" AppendDataBoundItems="true">
<asp:ListItem>-- pick one --</asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="drpClient" runat="server" Width="200px"
AutoPostBack="True" DataSourceID="dsClients" DataTextField="name"
DataValueField="client_id" AppendDataBoundItems="True">
<asp:ListItem Text="" Value="" />
</asp:DropDownList>
It's easy to miss, so don't forget the AppendDataBoundItems attribute I added.
I haven't really tested this but I'm assuming that you could add an item after you have binded the the drop down list. You could add this event to any dropdown list you'd like to add this empty box to.
protected void DropDownList_DataBound(object sender, EventArgs e)
{
DropDownList ddl = (DropDownList)sender;
ListItem emptyItem = new ListItem("", "");
ddl.Items.Insert(0, emptyItem);
}
I solve changing the select command adding an empty option:
<asp:SqlDataSource ID="dsClients" runat="server"
ConnectionString="my_connection_string"
ProviderName="System.Data.SqlClient"
SelectCommand="SELECT [client_id], [name] FROM [clients] union SELECT NULL, '--- pick one ----' ">
</asp:SqlDataSource>
Greetings!!!
In razor-style implementation at me it looks like this:
#Html.EnumDropDownListFor(
model => model.Privilege.Role,
"-- Select role --",
new
{
#style = "width: 216px !important",
#class = "form-control",
id = "role",
required = "required"
})
And in javascript which is executed on load I have this:
function PutDefaultPrivilegePanelListHints() {
$('#role').val('');
...
}
There is also more flexible solution via unobtrusive validation (not to count on HTML5):
$('.required').each(function () { $(this).rules('add', { required: true, messages: { required: '' } }) });
Of course, there is a server-side check, too.
I don't think it's a good idea to cope with classes.
For instance, everything I show in the page is some class. This class has several enumerable type properties. It would be a nightmare to replicate all those properties, but making them nullable in some additional class as some ones suggested here on stackoverflow.
After all, why should i change my business logic for the sake of some specific markup? Instead, I deal with everything via javascript and some model checks.

Inject record into DataList

I would like suggestions on how to inject a record into my DataList to give an "All" option. Here is my code, data coming from the Northwind database.
<asp:DataList ID="DataList1" runat="server" DataSourceID="SqlDataSource1"
RepeatLayout="Flow" ShowFooter="False" ShowHeader="False"
RepeatDirection="Horizontal"
onitemcommand="DataList1_ItemCommand">
<ItemStyle CssClass="datalist" />
<ItemTemplate>
<%#(((DataListItem)Container).ItemIndex+1).ToString() %>
<asp:LinkButton ID="lbtnRegion" runat="server"
Text='<%# Eval("RegionDescription").ToString().Trim() %>'
CommandName='<%# DataBinder.Eval(Container.DataItem,"RegionID")%>' />
</ItemTemplate>
</asp:DataList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
SelectCommand="SELECT [RegionID], [RegionDescription] FROM [Region]"
ondatabinding="SqlDataSource1_Databinding"
onselected="SqlDataSource1_Selected">
</asp:SqlDataSource>
I am using the Link button in the Datalist to filter the territories and display them in a GridView.
What I would like to do is at some in the databinding process, add an Item in the DataList that will act as the ALL option, any suggestions would be appreciated.
protected void DataList1_ItemCommand(object source, DataListCommandEventArgs e)
{
LinkButton lbtn;
foreach (DataListItem dli in DataList1.Items)
{
lbtn = (LinkButton)dli.FindControl("lbtnRegion");
if (lbtn != null)
lbtn.ForeColor = System.Drawing.Color.White;
}
string command = e.CommandName;
lbtn = (LinkButton)e.Item.FindControl("lbtnRegion");
if (lbtn != null)
lbtn.ForeColor = System.Drawing.Color.YellowGreen;
DataView dv = GetData(ref command); // Pass the RegionId
gvTerritory.DataSource = dv;
gvTerritory.DataBind();
}
Thanks
One way is to UNION ALL a 'All' value to the query fetching the list of drop down items.
SELECT 'All', 'All Regions'
UNION ALL
SELECT [RegionID], [RegionDescription] FROM [Region]
But if you have a lot of lists (or dropdowns) like this, it is better practice to create a custom control that injects an 'All' record for you.
It worked with the following SQL:
SELECT '-1' AS 'RegionID', 'All Regions' AS 'RegionDescription'
UNION ALL SELECT [RegionID], [RegionDescription] FROM [Region]
Used this on a drop down, may work the same on a datalist
Protected Sub ddlDataSources_DataBound(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddlDataSources.DataBound
ddlDataSources.Items.Insert(0, New ListItem("All Data Sources", 0))
End Sub

Resources