Bind ASP.NET DropDownList DataTextField to method? - asp.net

Is there anyway to have items in an ASP.NET DropDownList have either their Text or Value bound to a method on the source rather than a property?

This is my solution:
<asp:DropDownList ID="dropDownList" runat="server" DataSourceID="dataSource" DataValueField="DataValueField" DataTextField="DataTextField" />
<asp:ObjectDataSource ID="dataSource" runat="server" SelectMethod="SelectForDataSource" TypeName="CategoryDao" />
public IEnumerable<object> SelectForDataSource()
{
return _repository.Search().Select(x => new{
DataValueField = x.CategoryId,
DataTextField = x.ToString() // Here is the trick!
}).Cast<object>();
}

Here's 2 examples for binding a dropdown in ASP.net from a class
Your aspx page
<asp:DropDownList ID="DropDownListJour1" runat="server">
</asp:DropDownList>
<br />
<asp:DropDownList ID="DropDownListJour2" runat="server">
</asp:DropDownList>
Your aspx.cs page
protected void Page_Load(object sender, EventArgs e)
{
//Exemple with value different same as text (dropdown)
DropDownListJour1.DataSource = jour.ListSameValueText();
DropDownListJour1.DataBind();
//Exemple with value different of text (dropdown)
DropDownListJour2.DataSource = jour.ListDifferentValueText();
DropDownListJour2.DataValueField = "Key";
DropDownListJour2.DataTextField = "Value";
DropDownListJour2.DataBind();
}
Your jour.cs class (jour.cs)
public class jour
{
public static string[] ListSameValueText()
{
string[] myarray = {"a","b","c","d","e"} ;
return myarray;
}
public static Dictionary<int, string> ListDifferentValueText()
{
var joursem2 = new Dictionary<int, string>();
joursem2.Add(1, "Lundi");
joursem2.Add(2, "Mardi");
joursem2.Add(3, "Mercredi");
joursem2.Add(4, "Jeudi");
joursem2.Add(5, "Vendredi");
return joursem2;
}
}

The only way to do it is to handle the Databinding event of the DropDownList, call the method and set the values in the DropDownList item yourself.

Sometimes I need to use Navigation Properties as DataTextField, like ("User.Address.Description"), so I decided to create a simple control that derives from DropDownList.
I also implemented an ItemDataBound Event that can help as well.
public class RTIDropDownList : DropDownList
{
public delegate void ItemDataBoundDelegate( ListItem item, object dataRow );
[Description( "ItemDataBound Event" )]
public event ItemDataBoundDelegate ItemDataBound;
protected override void PerformDataBinding( IEnumerable dataSource )
{
if ( dataSource != null )
{
if ( !AppendDataBoundItems )
this.Items.Clear();
IEnumerator e = dataSource.GetEnumerator();
while ( e.MoveNext() )
{
object row = e.Current;
var item = new ListItem( DataBinder.Eval( row, DataTextField, DataTextFormatString ).ToString(), DataBinder.Eval( row, DataValueField ).ToString() );
this.Items.Add( item );
if ( ItemDataBound != null ) //
ItemDataBound( item, row );
}
}
}
}

Declaratively:
<asp:DropDownList ID="ddlType" runat="server" Width="250px" AppendDataBoundItems="true" DataSourceID="dsTypeList" DataTextField="Description" DataValueField="ID">
<asp:ListItem Value="0">All Categories</asp:ListItem>
</asp:DropDownList><br />
<asp:ObjectDataSource ID="dsTypeList" runat="server" DataObjectTypeName="MyType" SelectMethod="GetList" TypeName="MyTypeManager">
</asp:ObjectDataSource>
The above binds to a method that returns a generic list, but you could also bind to a method that returns a DataReader. You could also create your dataSource in code.

Related

Radio button to select one box only....ERROR

Something is wrong with the following code cause I can select more than one radiobutton at the same time.... How can I make the following code select only one radiobutton? Please help.
<asp:ListView ID="ListView1" runat="server" DataSourceID="SqlDataSource_BGlist">
<ItemTemplate>
<asp:RadioButton ID="Radio1" GroupName="BG_name" runat="server" Text='<%# Eval("BG_fileName") %>' />
<asp:Label ID="BG_fileNameLabel" runat="server" Text='<%# Eval("BG_fileName") %>' />
</ItemTemplate>
</asp:ListView>
The easiest way to accomplish this is to just wrap your listview in an ASP.NET Panel or GroupBox, and ASP will implement the grouping you want.
Adding a panel doesn't group radio buttons together if they are contained in some sort of repeater. Probably the best solution is to use a RadioButtonList as suggested in Grebets' Answer.
If that doesn't suit your needs you can use javascript to alter the radio buttons after they have been created. The following code will work when added to the bottom of your page:
<script type="text/javascript">
var inputElements = document.getElementsByTagName("input");
for (var inputName in inputElements) {
var input = inputElements[inputName];
if (input.type === "radio") {
input.name = "Group1";
}
}
</script>
The script can be simplified if you are using jQuery.
I think the most effective way will be use RadioButtonList:
<asp:RadioButtonList ID="RadioButtonList1" runat="server" DataTextField="BG_fileName" DataValueField="BG_fileName" DataSourceID="SqlDataSource_BGlist">
</asp:RadioButtonList>
And if you preffer to use datasources in codebehind (like I do):
public class MyClass
{
public string BG_fileName { get; set; }
public MyClass(string bgFileName)
{
BG_fileName = bgFileName;
}
}
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
RadioButtonList1.DataSource = new List<MyClass>
{
new MyClass("test string 1"),
new MyClass("test string 2"),
new MyClass("test string 3")
};
RadioButtonList1.DataBind();
}
}

Why do I have to click a button twice in an ASP.NET repeater to get the command to fire?

I have an ASP.NET page with the following 3 main areas:
1 - list of checkboxes on the left for fitlering results
2 - Repeater that displays the matching results in the middle (with a button for each item)
3 - Repeater that displays the selected items on the right
On initial page load the page will show the data bound checkboxes and will show all results (since nothing has been checked in the filters). As the user checks or unchecks the checkboxes, the page will reload and the matching results will change. So far this part works great.
In the Results Repeater, each item has a Button. When the user clicks the button for an item in the Results the idea is that the item will get added to the Selected Repeater on the right. What is happening is that after I check or uncheck filter checkboxes - the first time that I then try and click on the buttons in the Results repeater, nothing happens. The page just reloads. Then if I click the button a second time, the Repeater Command will fire and the item will get added to the Repeater on the right hand side. Then, as long as I don't change any of the checkboxes I can click on one of the command buttons and it will work right away. But if I check one of the checkboxes in the filters area (which causes the Results to get re-bound) then I have to click one of the buttons twice to get it to fire.
I have a sense that this has something to do with ViewState but I have no idea. Does anyone know why this would be happening?
Below is my code for both the ASPX page and the code behind.
ASPX Code:
<h3>Filters</h3>
<asp:Repeater ID="rptTechnologies" runat="server" OnItemDataBound="rptFacet_ItemDataBound">
<HeaderTemplate><h4>Technology</h4></HeaderTemplate>
<ItemTemplate><asp:CheckBox ID="chkFacet" runat="server" AutoPostBack="true" OnCheckedChanged="chkFacet_Changed" /><br /></ItemTemplate>
</asp:Repeater>
<asp:Repeater ID="rptVerticals" runat="server" OnItemDataBound="rptFacet_ItemDataBound">
<HeaderTemplate><h4>Vertical</h4></HeaderTemplate>
<ItemTemplate><asp:CheckBox ID="chkFacet" runat="server" AutoPostBack="true" OnCheckedChanged="chkFacet_Changed" /><br /></ItemTemplate>
</asp:Repeater>
<asp:Repeater ID="rptIndustries" runat="server" OnItemDataBound="rptFacet_ItemDataBound">
<HeaderTemplate><h4>Industry</h4></HeaderTemplate>
<ItemTemplate><asp:CheckBox ID="chkFacet" runat="server" AutoPostBack="true" OnCheckedChanged="chkFacet_Changed" /><br /></ItemTemplate>
</asp:Repeater>
<asp:Repeater ID="rptSolutions" runat="server" OnItemDataBound="rptFacet_ItemDataBound">
<HeaderTemplate><h4>Solution</h4></HeaderTemplate>
<ItemTemplate><asp:CheckBox ID="chkFacet" runat="server" AutoPostBack="true" OnCheckedChanged="chkFacet_Changed" /><br /></ItemTemplate>
</asp:Repeater>
<h3>Results</h3>
<asp:Repeater ID="rptMatchingSlides" runat="server" OnItemDataBound="rptMatchingSlides_ItemDataBound" OnItemCommand="rptMatchingSlides_Command">
<ItemTemplate>
<h4><asp:Literal ID="litName" runat="server"></asp:Literal></h4>
<asp:Button ID="btnSelect" runat="server" Text="Select" CommandName="Select" />
</ItemTemplate>
<SeparatorTemplate><hr /></SeparatorTemplate>
</asp:Repeater>
<h3>Selected</h3>
<asp:Repeater ID="rptSelectedSlides" runat="server" OnItemDataBound="rptSelectedSlides_ItemDataBound">
<ItemTemplate>
<h4><asp:Literal ID="litName" runat="server"></asp:Literal></h4>
</ItemTemplate>
<SeparatorTemplate><hr /></SeparatorTemplate>
</asp:Repeater>
Here is the code behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
this.BindData();
}
}
public List<string> SelectedSlides
{
get
{
if (Session["SelectedIDs"] != null)
{
string[] _ids = Session["SelectedIDs"].ToString().Split(new char[] { '|' });
List<String> _retVal = new List<string>();
foreach (string _id in _ids)
{
_retVal.Add(_id);
}
return _retVal;
}
else
{
return new List<string>();
}
}
set
{
//Set the session value
string _val = "";
foreach (string _id in value)
{
if (_val == "")
{
_val = _id;
}
else
{
_val += "|" + _id;
}
}
Session["SelectedIDs"] = _val;
}
}
protected void BindData()
{
//Filters
rptTechnologies.DataSource = Repository.GetTaxonomyItems();
rptTechnologies.DataBind();
rptVerticals.DataSource = Repository.GetTaxonomyItems();
rptVerticals.DataBind();
rptIndustries.DataSource = Repository.GetTaxonomyItems();
rptIndustries.DataBind();
rptSolutions.DataSource = Repository.GetTaxonomyItems();
rptSolutions.DataBind();
this.BindMatchingSlides();
}
protected void BindMatchingSlides()
{
...build list of ids from checkboxes...
rptMatchingSlides.DataSource = Repository.GetMatchingSlides(_selectedIDs);
rptMatchingSlides.DataBind();
}
protected void BindSelectedSlides()
{
if (this.SelectedSlides.Count > 0)
{
rptSelectedSlides.DataSource = this.SelectedSlides;
rptSelectedSlides.DataBind();
}
else
{
divSelectedSlides.Visible = false;
}
}
protected void rptMatchingSlides_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
Literal _litName = (Literal)e.Item.FindControl("litName");
Button _btnSelect = (Button)e.Item.FindControl("btnSelect");
_litName.Text = ...set name here...
_btnSelect.CommandArgument = ...use unique ID of item from database...
_btnSelect.ID = "btnSelect_" + e.Item.ItemIndex;
}
}
protected void rptMatchingSlides_Command(object sender, RepeaterCommandEventArgs e)
{
if (e.CommandName == "Select")
{
Item _slide = ...get data from database based on Command Argument...
if (_slide != null)
{
List<string> _selectedSlides = this.SelectedSlides;
_selectedSlides.Add(_slide.ID.ToString());
this.SelectedSlides = _selectedSlides;
}
this.BindSelectedSlides();
}
}
Thanks to Jeremy - removing the line of code where I was setting the ID fixed it. Doh! Somewhere else I had read that you needed to set a unique value for the IDs of the buttons in a repeater. So that must have been the culprit. Thanks to Jeremy.

ListView + ObjectDataSource SelectMethod called twice when EnableViewState="false"

Note: This question has been completely modified now that I have a simpler example.
I have set up a sample page which only has a ListView and ObjectDataSource. The first time the page comes up (!IsPostBack), my GetList method is called once. After paging (IsPostBack), the GetList method is called twice--the first time with the old paging values and the second time with the new values.
If I set EnableViewState="true" on the ListView, then the GetList method is only called once. It seems to me that the ListView wants an "initial state", which it either gets from ViewState or by re-running the method.
Is there any way to disable ViewState on the ListView and also prevent SelectMethod from being called twice?
ASPX page:
<asp:ListView ID="TestListView" runat="server" DataSourceID="ODS" EnableViewState="false">
<LayoutTemplate>
<asp:PlaceHolder ID="itemPlaceHolder" runat="server" />
<asp:DataPager ID="TestPager" runat="server" PageSize="10">
<Fields>
<asp:NumericPagerField />
</Fields>
</asp:DataPager>
</LayoutTemplate>
<ItemTemplate>
<div><%# Eval("Title") %></div>
</ItemTemplate>
</asp:ListView>
<asp:ObjectDataSource ID="ODS" runat="server" SelectMethod="GetList" SelectCountMethod="GetListCount"
TypeName="Website.Test" EnablePaging="true" />
ASPX code-behind:
namespace Website
{
public partial class Test : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
public IList<DataItem> GetList(int maximumRows, int startRowIndex)
{
return GetListEnumerable().Skip(startRowIndex).Take(maximumRows).ToList();
}
public IEnumerable<DataItem> GetListEnumerable()
{
for (int i = 0; i < 100; i++)
{
yield return new DataItem { Title = i.ToString() };
}
}
public int GetListCount()
{
return 100;
}
}
public class DataItem
{
public string Title { get; set; }
}
}
Either turn ODS caching on.
<asp:ObjectDataSource ID="ODS" ... EnableCaching="true" />
This way the GetList will be called only when new data is needed. Post backs to pages that already had data retrieved will use the cached version and not call the GetList.
Or move your DataPager out of the ListView and set the PagedControlID property.
Actually you should be using the OnSelecting event.
What happens is that ObjectDataSource calls the method SelectMethod twice
First time it gets the data.
Next time it gets the count.
So I think you have to implement the OnSelecting event
<asp:ObjectDataSource ID="ODS" runat="server" SelectMethod="GetList" SelectCountMethod="GetListCount"
OnSelecting="ods_Selecting">
TypeName="Website.Test" EnablePaging="true" />
and then cancel the event when the ObjectDataSource tries to call the count method.
protected void ods_Selecting(object sender,
ObjectDataSourceSelectingEventArgs e)
{
if (e.ExecutingSelectCount)
{
//Cancel the event
return;
}
}
You can look for full implementation as mentioned in the link below
http://www.unboxedsolutions.com/sean/archive/2005/12/28/818.aspx
Hope this helps.
I had a similar problem where it worked different depending on browser. IE one way and all other browsers one way.. Might not be the same issue as you have.
I solved it this way:
protected void DropDownDataBound(object sender, EventArgs e)
{
// Issue with IE - Disable ViewState for IE browsers otherwhise the dropdown will render empty.
DropDownList DDL = (DropDownList)sender;
if (Request.Browser.Browser.Equals("IE", StringComparison.CurrentCultureIgnoreCase))
DDL.ViewStateMode = System.Web.UI.ViewStateMode.Disabled;
else
DDL.ViewStateMode = System.Web.UI.ViewStateMode.Inherit;
}

getting attributes from aspx-page

i have an aspx-page which contains a detailsview.
this detailsview contains one or more templated-fields.
what i need is a additional attribute (or metadata information) to determite the bound datafield.
some thing like that would be nice (simplified):
<asp:DetailsView>
<fields>
<TemplateField DataField="DataField1">
...
</TemplateField>
</fields>
</asp:DetailsView>
is it possible to get attribute "DataField" ?
otherwise i will subclassing TemplateField and add a property :)
I haven't done that for a while, but I seem to remember if you add a public set/get "DataField" property to the TemplateField class, ASP.NET should automatically initialize it with the value you pass in the attribute.
i thought subclassing of TemplateField will do the job:
[AspNetHostingPermission(SecurityAction.Demand, Level=AspNetHostingPermissionLevel.Minimal)]
[DefaultProperty("DataField")]
public class DataTemplateField : TemplateField
{
private String _dataField;
public String DataField
{
get {
return _dataField;
}
set {
_dataField = value;
}
}
}
now u can use this field in detailsview like this
<Fields>
<dvt:DataTemplateField HeaderText="Feld1" DataField="DIS">
<ItemTemplate>
<asp:Button runat="server" Text="Button" />
</ItemTemplate>
</dvt:DataTemplateField>
</Fields>
and get that data
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
foreach(DetailsViewRow row in DetailsView1.Rows)
{
DataControlFieldCell cell = (DataControlFieldCell)row.Cells[1];
if (cell.ContainingField is DataTemplateField)
{
var field = (DataTemplateField)cell.ContainingField;
cell.Enabled = !field.DataField.Equals(fieldToDisable);
}
}
}

GridView FindControl returns null when HeaderText is set

I have a GridView...
<asp:GridView EnableViewState="true"
ID="grdResults"
runat="server"
CssClass="resultsGrid"
OnRowDataBound="grdResults_OnRowDataBound"
AutoGenerateColumns="false"
HeaderStyle-CssClass="header"
OnRowCommand="grdResults_OnRowCommand">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblView"
runat="server"
Visible="false"
Text="View">
</asp:Label>
<asp:HyperLink ID="hypEdit"
runat="server"
Visible="false"
Text="(Edit)"
CssClass="edit">
</asp:HyperLink>
<asp:LinkButton ID="btnDelete"
runat="server"
Visible="false"
Text="(Delete)"
CssClass="delete"
CommandName="DeleteItem"
OnClientClick="return confirm('Are you sure you want to delete?')">
</asp:LinkButton>
<asp:HyperLink ID="hypSelect"
runat="server"
Visible="false"
Text="(Select)"
CssClass="select">
</asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
This has one static column containing a label two hyperlinks and a link button and also has a number of dynamically generated columns...
private void SetupColumnStructure(IEnumerable<string> columnNames)
{
var columnNumber = 0;
foreach (var columnName in columnNames)
{
var templateColumn = new TemplateField
{
ItemTemplate = new CellTemplate(columnName)
};
grdResults.Columns.Insert(columnNumber, templateColumn);
columnNumber++;
}
}
As part of the OnRowDataBound handler I retrieve one of the controls in the statically column and set some attributes on it...
protected void grdResults_OnRowDataBound(object sender, GridViewRowEventArgs e)
{
.
.
.
var row = e.Row;
var rowData = row.DataItem as Dictionary<string, object>;
if (rowData != null)
{
if ((bool)rowData[displayEditLink])
{
var hypEdit = (HyperLink)row.FindControl("hypEdit");
hypEdit.NavigateUrl = "~/Pages/Edit.aspx?action=Edit&objectType=" + rowData[objectTypeLiteral] + "&id=" + rowData[objectIdLiteral];
hypEdit.Visible = true;
}
}
.
.
.
}
This all works fine but no column names are displayed. So I then modify the SetupColumnStructure method so that the HeaderText is set on the template field like this...
private void SetupColumnStructure(IEnumerable<string> columnNames)
{
var columnNumber = 0;
foreach (var columnName in columnNames)
{
var templateColumn = new TemplateField
{
ItemTemplate = new CellTemplate(columnName),
HeaderText = columnName
};
grdResults.Columns.Insert(columnNumber, templateColumn);
columnNumber++;
}
}
For some reason this one extra line change causes the row.FindControl("hypEdit"); call in the OnRowDataBound handler to return null.Can anyone see something im missing here or has anyone experienced a similar issue?
UPDATE
I've made sure that I'm not referring to a header or footer row here. Also, if I step over the object reference exception this occurs for every item that is in the DataSource.
Not sure if this helps, but as I expected, when I stepped through the code the table has generated all the columns expected but all cells (DataControlFieldCells) contain no controls when the HeaderText is set, yet all expected controls when it isnt set.
All very strange. Let me know if you can spot anything else.
When you added the HeaderText, a new RowType was added to the gridview. You'll need to check what type of row raised the OnRowDataBound event and take the appropriate action. In your case, just checking if the e.Row.RowType is a DataRow should solve your problem:
protected void grdResults_OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
if ((bool)rowData[displayEditLink])
{
var hypEdit = (HyperLink)row.FindControl("hypEdit");
hypEdit.NavigateUrl = "~/Pages/Edit.aspx?action=Edit&objectType=" + rowData[objectTypeLiteral] + "&id=" + rowData[objectIdLiteral];
hypEdit.Visible = true;
}
}
}
Its because the control you are searching for is contained within another control. FindControl() does not look inside control collections of controls. You will need to write a recursiveFindControl() method.
Hope this helps a little!

Resources