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();
Related
I have a datalist in my asp.net page. I bind a datasource to it in codebehind
and I have a checkbox in this datalist.
var n = from gi in DataContext.Context.GalleryImages
join g in DataContext.Context.Galleries
on gi.GalleryID equals g.GalleryID
where g.UserID == UserID && gi.GalleryID==GalleryID
select new
{
GalleryID = g.GalleryID,
ImageDescription = gi.ImageDescription,
GalleryName = g.GalleryName,
ImageFileName = gi.ImageFileName,
IsAlbumImage = gi.IsAlbumImage,
ImageID=gi.ImageID
};
dlGalleryList.DataSource = n;
dlGalleryList.DataBind();
When the "IsAlbumImage " is true the checkbox should be checked.
How can I bind this property to the checkbox?
It should be bind like:
<ItemTemplate>
<asp:CheckBox id="MyCheckBox" runat="server" Checked='<%#Eval("IsAlbumImage") %>' />
</ItemTemplate>
Actually you have to ways to bind checkbox in a datalist
1- (recommended) Binding it directly from the ASP code using the Bind or Eval
<ItemTemplate>
<asp:CheckBox id="MyCheckBox" runat="server" Checked='<%#Eval("IsAlbumImage") %>' />
</ItemTemplate>
2- Binding it on the ItemDataBound Event
First you will add the event handler to your datalist control, and adds the Boolean value to a datakey to be used in itemdatabound event
<asp:DataList ID = "DataList1" OnItemDataBound="DataListItemEventHandler" DataKeys = "IsAlbumImage"/>
Then you add the C# code that bind this
protected void DataListItemEventHandler(object sender, DataListItemEventArgs e)
{
CheckBox checkbx = new CheckBox();
checkbx = (CheckBox)e.Item.FindControl("MyCheckBox");
checkbx.Checked = (bool) DataList1.DataKeys(e.Item.ItemIndex)("IsAlbumImage");
}
Like this:
<asp:CheckBox
ID="check"
runat="server"
Checked='<%# Eval("column_name").ToString().Equals("1") %>'
/>
I have a page with gridview in it.
My gridview shows the products Information and Admin can Edit gridviews columns.
Two of my columns show the brand name and category name for each product;
I use lables in ItemTemplate tag in my grid view to show these two columns value and I use two dropdownlists(branddrop,categorydrop)
in my EditItemTemplate tag for editing these two columns value,when admin select an item in branddrop the categorydrop should show categories name which are related to selected brand name in branddrop.
Brands name in my brand table in database are:
Samsung, Nokia,Sony Ericsson,Apple,LG,HTC....
and my categories name in category table are :
Galaxy Nexus,Galaxy Tab 2 7. 0,Galaxy S3,Asha,Lumia,iPhone,iPad,Xperia Arc,Xperia Neo,Xperia X8,Cookie 3g,Cookie lite,Km555e,Optimus l9,Optimus elite,Optimus g,wt18i,w8,500,n8...
When I click the Edit button, first item in the branddrop is Equal to brandlable.
Text in ItemTemplate and it works fine my problem is the first item in category drop is not Equal to categorylable.text in ItemTemplate and the category drop does not show the related categories name to brandname.for every product it shows iphone and ipad so I have to select another items in branddrop and then select again the related brandname which is related to that product then the categorydrop can show the list of related categories name.I tried to use brandDrop_SelectedIndexChanged and GridView1_RowEditing but it is not work. I dont know how to solve it.
this is my first code:
<asp:TemplateField HeaderText="brand name">
<ItemTemplate>
<asp:Label ID="brandname" runat="server" Text='<%#Eval("brand_name") %>'></asp:Label>
<asp:Label ID="idfrombrand" runat="server" Text='<%#Eval("idfrombrands") %>' Visible="false"></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="br" runat="server" Text='<%# Eval("idfrombrands") %>' Visible="false"></asp:Label><%--OnSelectedIndexChanged="brandDrop_SelectedIndexChanged" --%>
<asp:DropDownList ID="brandDrop" runat="server" DataTextField="brand_name" DataValueField="id" DataSourceID="SqlDataSource4" AutoPostBack="true" OnSelectedIndexChanged="brandDrop_SelectedIndexChanged" >
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource4" runat="server" ConnectionString="<%$ ConnectionStrings:mobile_storeConnectionString2 %>" SelectCommand="select [id],[brand_name] from [brands]" ></asp:SqlDataSource>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="category name">
<ItemTemplate>
<asp:Label ID="catname" runat="server" Text='<%# Eval("category_name") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="OldCatName" runat="server" Text='<%# Eval("idfromCategories") %>' Visible="false"></asp:Label>
<asp:DropDownList ID="categoryDrop" runat="server" AutoPostBack="true" DataTextField="category_name" DataValueField="id" DataSourceID="SqlDataSource3"> <%-- --%>
</asp:DropDownList>
<asp:Label ID="cat" runat="server" Text='<%# Eval("idfromCategories") %>' Visible="false" ></asp:Label>
<asp:SqlDataSource ID="SqlDataSource3" runat="server" ConnectionString="<%$ ConnectionStrings:mobile_storeConnectionString2 %>" SelectCommand="select [category_name],[id],[idfrombrands] from [categories] where idfrombrands=#idfrombrands " >
<SelectParameters>
<asp:ControlParameter ControlID="brandDrop"
Name="idfrombrands" PropertyName="SelectedValue" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
</EditItemTemplate>
</asp:TemplateField>
this is my code behind for GridView1_RowDataBound and GridView1_RowUpdating:
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int brand=0;
int category=0;
//Drop Brand--------------------------------------
DropDownList list1 = (DropDownList)GridView1.Rows[e.RowIndex].FindControl("brandDrop");
Label lbl = (Label)GridView1.Rows[e.RowIndex].FindControl("br");
if (list1.SelectedItem.Value != null)
{
brand = Convert.ToInt32(list1.SelectedItem.Value);//NewIdFromBrand
}
else
{
brand = Convert.ToInt32(lbl.Text);
}
//Drop Category----------------------------------------
DropDownList list2 = (DropDownList)GridView1.Rows[e.RowIndex].FindControl("categoryDrop");
Label lbl2 = (Label)GridView1.Rows[e.RowIndex].FindControl("OldCatName");
//int NewIdFromBrand2 = -1;
if (list2.SelectedItem.Value != null)
{
category = Convert.ToInt32(list2.SelectedItem.Value);//NewIdFromBrand2
}
else
{
category = Convert.ToInt32(lbl2.Text);
}
//Photo-------------------------------------------
string photoname = System.Guid.NewGuid().ToString();
GridViewRow row = GridView1.Rows[e.RowIndex];
FileUpload fileUpload = row.FindControl("FileUploadimg") as FileUpload;
Label lbl3 = (Label)GridView1.Rows[e.RowIndex].FindControl("oldImage");
if (fileUpload != null && fileUpload.HasFile)
{
fileUpload.SaveAs(Server.MapPath("~/P_Image") + photoname + fileUpload.FileName);
SqlDataSource1.UpdateParameters["path"].DefaultValue = "~/P_Image" + photoname + fileUpload.FileName;
}
else
{
SqlDataSource1.UpdateParameters["path"].DefaultValue = lbl3.Text;//oldImage.Text;
}
int prid = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value);
SqlConnection cn = new SqlConnection();
cn.ConnectionString = "server = . ; database = mobile_store ; Trusted_Connection=true";
DataTable tb = new DataTable();
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "UpdateProduct";
cmd.Parameters.AddWithValue("#brandid", brand );
cmd.Parameters.AddWithValue("#catid", category );
cmd.Parameters.AddWithValue("#pid", prid);
try
{
cn.Open();
cmd.ExecuteNonQuery();
SqlDataSource1.DataBind();
}
catch (Exception ex2)
{
}
finally { cn.Close(); }
//GridView1.EditIndex = -1;
//GridView1.DataBind();
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//check if is in edit mode
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
DataRowView dRowView1 = (DataRowView)e.Row.DataItem;
if (e.Row.RowType == DataControlRowType.DataRow)
{
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
DropDownList ddlStatus = (DropDownList)e.Row.FindControl("brandDrop");
ddlStatus.SelectedValue = dRowView1["brandId"].ToString();
DropDownList ddlStatus2 = (DropDownList)e.Row.FindControl("categoryDrop");
ddlStatus2.SelectedValue = dRowView1["categoryID"].ToString();
//Label1.Text = ddlStatus.SelectedValue;
}
}
}
}
}
Thank you so much Abide Masaraure.you helped me a lot.
I deleted grideview_rowediting and braddrop_selectedIndexChange event And just added two lines to my GridView1_RowDataBound event.
SqlDataSource sq = (SqlDataSource)e.Row.FindControl("SqlDataSource3");
sq.SelectParameters["idfrombrands"].DefaultValue = dRowView1["brandId"].ToString();
now my event is like this:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//check if is in edit mode
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
DataRowView dRowView1 = (DataRowView)e.Row.DataItem;
if (e.Row.RowType == DataControlRowType.DataRow)
{
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
DropDownList ddlStatus = (DropDownList)e.Row.FindControl("brandDrop");
ddlStatus.SelectedValue = dRowView1["brandId"].ToString();
DropDownList ddlStatus2 = (DropDownList)e.Row.FindControl("categoryDrop");
ddlStatus2.SelectedValue = dRowView1["categoryID"].ToString();
SqlDataSource sq = (SqlDataSource)e.Row.FindControl("SqlDataSource3");
sq.SelectParameters["idfrombrands"].DefaultValue = dRowView1["brandId"].ToString();
}
}
}
}
}
Eureka!!!.You owe me a cup of coffee.I replicated your problem and realized after two hours that you need to actually hook to your index selected changed event.The trick is to use the naming container property to locate your drop downs,they think are pretty hidden ,but the sender argument enables us to expose them when dropband dropdown fires. And presto everything works like a charm.
Use this code snipet in your selected changed event.
protected void dropBand_SelectedIndexChanged(object sender, System.EventArgs e)
{
DropDownList dropBand = (DropDownList)sender;
SqlDataSource dsc = (SqlDataSource)dropBand.NamingContainer.FindControl("SqlDataSource3");
DropDownList categoryDrop = (DropDownList)dropBand.NamingContainer.FindControl("categoryDrop");
dsc.SelectParameters("BrandID").DefaultValue = dropBand.SelectedValue;
categoryDrop.DataBind();
}
I can send you a zip file of the demo this time if you happen to continue having issue.Happy Coding!!!.
I need to see your code you are using in your selected index changed event.
The following cascading drop down technique will take away all the suffering you have in trying to hook up the parent and its children...I use this wonderful feature in the Ajax control toolkit in all my projects.You can use any data retrieval method you want as long it returns an array.I am using linq in this example for data retrieval.
Assuming I have tables named Brand and Model and classes : Brand and Model and collections: Brands and Models
In 'YourWebServicePath.asmx' (Web service file)
<WebMethod()> _
Public Function GetBrands(knownCategoryValues As String, category As String) As CascadingDropDownNameValue()
Dim result = From b As Bands In Brand.Brands Select New CascadingDropDownNameValue(b.BrandDesc, b.BrandID.ToString())
Return result.ToArray()
End Function
<WebMethod()> _
Public Function GetModels(knownCategoryValues As String, category As String) As CascadingDropDownNameValue()
Dim brandID As Guid
Dim brandValues As StringDictionary = AjaxControlToolkit.CascadingDropDown._
ParseKnownCategoryValuesString(knownCategoryValues)
brandID = New Guid(brandValues("Brand"))
Dim result = From m As Models In Model.GetModels() Where m.brandID = brandID Select New CascadingDropDownNameValue(m.ModelDesc,
_ m.ModelID.ToString())
Return result.ToArray()
End Function
MarkUp
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>
<EditItemTemplate>
<asp:DropDownList ID="dropBrand" runat="server" AutoPostBack="true" >
</asp:DropDownList>
<cc1:CascadingDropDown ID="BrandCascadingDropDown"
runat="server"
Category="Brand"
TargetControlID="dropBrand"
PromptText="-Select Brand-"
LoadingText="Loading Brands.."
ServicePath="YourWebServicePath.asmx"
ServiceMethod="GetBrands">
</cc1:CascadingDropDown>
</EditItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="dropModel" runat="server" AutoPostBack="true" >
</asp:DropDownList>
<cc1:CascadingDropDown ID="ModelCascadingDropDown"
runat="server"
Category="Model"
TargetControlID="dropModel"
ParentControlID="dropBrand"
PromptText="-Select Model-"
LoadingText="Loading Models.."
ServicePath="YourWebServicePath.asmx"
ServiceMethod="GetModels" >
</cc1:CascadingDropDown>
And thats all you need.No need of wiring the events.And voila! let the toolkit perform the magic.
To use the above code i gave you in a row editing event you have to modify it like so.Then those objects won't be null.
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView testgrid = (GridView)(sender);
testgrid.EditIndex = e.NewEditIndex;
testgrid.DataBind();
DropDownList dropBand = (DropDownList)testgrid.Rows[e.NewEditIndex].FindControl("ddlProducts");
//
}
Something is definitely happening in your page cycle and is keeping on biting you.I suggest zip an mdf of your database and the offending aspx page and let me tackle it from here if you don't get it to work.Never give up.
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.
Is there some elegant way to add an empty option to a DropDownList bound with a LinqDataSource?
Here's how to add a value at the top of the list. It can be an empty string, or some text.
<asp:DropDownList ID="categories" runat="server" AppendDataBoundItems="True" AutoPostBack="True" DataSourceID="categoriesDataSource" DataTextField="CategoryName" DataValueField="CategoryID" EnableViewState="False">
<asp:ListItem Value="-1">
-- Choose a Category --
</asp:ListItem>
</asp:DropDownList>
Be sure to set the DropDownList's AppendDataBoundItems=True.
Markup:
<asp:DropDownList ID="ddlQualQuestion" runat="server" DataSourceID="sdsQualQuestion" DataTextField="ShortQuestionText" DataValueField="QualificationQuestionKey" AutoPostBack="true" OnSelectedIndexChanged="ddlQualQuestion_SelectedIndexChanged" OnDataBound="ddlQualQuestion_DataBound" />;
Code behind:
protected void ddlQualQuestion_DataBound(object sender, EventArgs e)
{
ddlQualQuestion.Items.Insert(0, new ListItem("", "0"));
}
Taking the solution DOK provided:
<asp:DropDownList ID="categories" runat="server" AppendDataBoundItems="True" AutoPostBack="True" DataSourceID="categoriesDataSource" DataTextField="CategoryName" DataValueField="CategoryID" EnableViewState="False">
<asp:ListItem Value="-1">
-- Choose a Category --
</asp:ListItem>
</asp:DropDownList>
Addtionally, if you don't want to force the user to make a selection you can add a method to the LinqDataSource of your GridView:
OnSelecting="myGridview_Selecting"
Add code behind like this:
protected void myGridview_Selecting(object sender, LinqDataSourceSelectEventArgs e)
{
if (categories.SelectedValue == "-1")
{
e.WhereParameters.Remove("CategoryID");
}
}
I'd provide an extension method on IEnumerable<string> that prepended an item to the beginning of the list:
public static IEnumerable<string> Prepend(this IEnumerable<string> data, string item)
{
return new string[] { item == null ? string.Empty : item }.Union(data);
}
Its sort of linq-y, as it uses the linq extension method Union. Its a little cleaner than doing this:
var result = new string[]{string.Empty}.Union(from x in data select x.ToString());
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