Bind a DropDownList to IEnumerable - asp.net

I have a method:
public static IEnumerable<Datarow> getInfo (string test)
{
some functionality and adds two columns in datatable dt.
now how can i return dt from this method (question 1)
}
I have to bind the method returned value to a dropdown list named ddlist .
How can i make it possible
(question no 2.)
.. when i tried i get the message that can not bind ienumerable . . . .
please help me out.

You could change the method to return a datatable or loop through the IEnumerable and add the list items manually.
Check this blog post for another approach to what you're trying to do. http://geekswithblogs.net/mikethomas/archive/2007/01/15/103686.aspx
Code sample from blog (not mine):
public IEnumerable GetDataSource() {
string key = "CodeDrowDownListTest_" + CodeName;
object item = Page.Cache.Get(key);
if (item == null)
{
item = GetDataFromDB();
Page.Cache.Insert(key, item, null, System.DateTime.UtcNow.AddHours(1), System.Web.Caching.Cache.NoSlidingExpiration);
}
return (IEnumerable)item; }
public override void DataBind() {
this.DataSource = GetDataSource();
this.DataTextField = "Text";
this.DataValueField = "Value";
base.DataBind();
}

Related

Bind repeater list with enum

I have a requirement where when a user clicks on image a list should be shown with checkboxes and all the categories that is present in DB and user should be able to select the checkboxes. How can this be achieved using asp:repeater control? the caegory is a enum type and can have n number of values. In repeater i have added a checkbox and a label; the label should display the category text.
To start with, you should add the [Description] attribute to each value in your Enum. This allows you to set proper descriptive text for each value. This attribute is in System.ComponentModel, here's an example: -
public enum CalendarShowAsEnum
{
[Description("None")]
None = 10,
[Description("Busy")]
Busy = 20,
[Description("Out Of Office")]
OutOfOffice = 30,
[Description("On Holiday")]
OnHoliday = 40
}
You then need 2 functions: -
One function that takes an Enum type and a ListBox/DropDown as parameters, and adds an entry for each Enum into the list
A helper function that converts the enum into the descriptive title you gave them (example above)
The List function might look as follows (all this is taken from a project I worked on): -
public static void BindNamedEnumList(ListControl list,
Type enumerationType)
{
list.Items.Clear();
Array array = Enum.GetValues(enumerationType);
ListItem item;
string name;
var enumerator = array.GetEnumerator();
if (enumerator != null)
{
while (enumerator.MoveNext())
{
Enum value = enumerator.Current as Enum;
name = EnumHelper.GetEnumName(value);
item = new ListItem(name);
item.Value = Convert.ToInt32(value).ToString();
list.Items.Add(item);
}
}
}
This function takes a Type and a ListControl (which ListBox and DropDownList both inherit from). The Type is the .GetType() of the enum you want to add to the list. Note that it doesn't select any values and that it does depend on each enum value having a defined integer value. The latter part will help you with selecting individual items.
Note the loop calls EnumHelper.GetEnumName(value) - this is the helper function that uses the Description attribute I mentioned at the start. This function looks like: -
public static string GetEnumName(object value)
{
string retVal = string.Empty;
try
{
FieldInfo fieldInfo = value.GetType().GetField(value.ToString());
DescriptionAttribute[] attributes = (DescriptionAttribute[])fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
retVal = ((attributes.Length != 0) ? attributes[0].Description : value.ToString());
}
catch (System.NullReferenceException)
{
}
finally
{
if (string.IsNullOrEmpty(retVal))
{
retVal = "Unknown";
}
}
return retVal;
}
It uses reflection, so you'll need to add an Imports for System.Reflection
To use the list function to bind a set of Enum values to the list, simply call
{HelperClass}.BindNamedEnumList(myListBox, typeof({MyEnumType})

How do you make a class method modify itself?

asp.net C#4
I have a simple class to working with query strings.
A new instance is created like this:
public QueryString(string querystring)
{
try
{
_table = new Hashtable();
if (querystring.Length > 0)
{
foreach (string pair in querystring.Split('&'))
{
string[] item = pair.Split('=');
_table.Add(item[0].ToLower(), item[1]);
}
}
}
catch (Exception)
{
}
}
I want to add a method to this that will remove a key value pair. I don't want it to return a new querystring, I just want it to remove the pair from the current instance. Not sure how to do that since it says I can't assign a value to 'this'
public void Remove(string key)
{
String querystring = this.ToString();
try
{
_table = new Hashtable();
if (key.Length > 0)
{
foreach (string pair in querystring.Split('&'))
{
string[] item = pair.Split('=');
if (item[0] != key)
{
_table.Add(item[0].ToLower(), item[1]);
}
}
this = _table;
}
}
catch (Exception)
{
}
}
You're overcomplicating things. Since your class's state is made up of the _table field, all you need to do is remove the item with the given key from that field.
The following example replaces your untyped Hashtable wit a strongly-typed Dictionary. I also chose to initialize the dictionary with a LINQ statement, but you could keep your old code there if you prefer.
public class QueryString
{
private readonly Dictionary<string, string> _table;
public QueryString(string querystring)
{
if (querystring.Length > 0)
{
var pairs =
from pair in querystring.Split('&')
let item = pair.Split('=')
select new {key = item[0], value = item[1]};
_table = pairs.ToDictionary(p => p.key, p => p.value);
}
}
public void Remove(string key)
{
_table.Remove(key);
}
}
You cannot assign a value to this since it is a reference to the object itself.
However, if you remove the line this = _table; , isn't things working as they should then? I guess your ToString() is somewhat using the hashtable to generate a "printer friendly" QueryString, and if that is the case, the way I see it, your Remove() method should be working (since you are replacing the _table variable with a new HashTable not including the key-value pair you want to exclude).
you are passing a querystring into the class so the original querystring IS intact.
However you then break down the querystring into a a Hashtable of key/value pairs. If you want to keep THAT intact you need to clone the HashTable and perform the remove on the clone.
In any case it's probably a good idea to keep the querystring you are passing in as a constructor parameter in a member variable for safe keeping.

Get Boolean Value of Each CheckList Items from Content Item in Sitecore

I have an item in Sitecore that contains a content section which is a Checklist. This checklist contains the names of multiple Active Directory groups that I have entered into Sitecore.
When the item loads, I am trying to loop through all of the check boxes that are in the Checklist to see if it is selected.
With help on a previous post, I was able to obtain the names that are listed next to each checkbox by using the following code (You can also see the commented out code that I tried using in order to obtain the value of he checkbox.):
Dim ADCheckList As Sitecore.Data.Fields.MultilistField = Sitecore.Context.Item.Fields("ADGroupAccess")
If ADCheckList IsNot Nothing Then
Dim i As Integer = 0
For i = 0 To ADCheckList.Count - 1
If IsInGroup(ADCheckList.GetItems(i).Fields("name").Value.ToString) Then
Response.Write("User in group. Now let's see if the group is checked.")
''' Trying to see if checkbox is checked or not.
''' Dim isChecked = DirectCast(ADCheckList.GetItems(i).Fields("name").Section, Boolean)
End If
Next
End IF
How can I obtain boolean value of the checkbox?
The field-type only stores the IDs of the items you have selected (as a pipe delimited list) it doesn't store the whole list of possibilities.
If you look at the Template that the item is created from you will see the datasource of the field. This will be a path to an item ie /sitecore/content/home/myfolderofthings the children of this item will be the options you see in the checklist.
You can, for example, loop through the items in the datasource location, get their item.ID property and see if ADCheckList.Items.Contains(item.ID) (or something similar) to get a boolean value.
Stephen's answer correctly pointed out that the checklist field only stores the pipe delimited list of selected IDs, you can see this by viewing the raw values in the content editor or Sitecore Rocks.
I've included some example code that has methods to get a list of all the items shown in a checklist as well as a method to retrieve only the selected items. I hope this helps.
using System;
using System.Collections.Generic;
using Sitecore.Data.Fields;
using Sitecore.Data.Items;
namespace Cms.Website.layouts
{
public partial class CheckList_SO : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
var contextItem = Sitecore.Context.Item;
const string checkListFieldName = "List";
SelectedItems.DataSource = contextItem.SelectedItemsInChecklist(checkListFieldName);
SelectedItems.DataBind();
FullItemList.DataSource = contextItem.AllItemsInChecklist(checkListFieldName);
FullItemList.DataBind();
}
}
}
public static class ItemExtensions
{
private static readonly Item[] EmptyItemArray = new Item[] { };
public static IEnumerable<Item> AllItemsInChecklist(this Item item, string checkListFieldName)
{
var fieldItem = item.Template.GetField(checkListFieldName);
if (fieldItem != null)
{
var listSource = fieldItem.Source;
if (!string.IsNullOrEmpty(listSource))
{
var sourceRoot = Sitecore.Context.Database.GetItem(listSource);
if (sourceRoot != null)
{
return sourceRoot.Children.ToArray();
}
}
}
return EmptyItemArray;
}
public static IEnumerable<Item> SelectedItemsInChecklist(this Item item, string checkListFieldName)
{
MultilistField checklist = item.Fields[checkListFieldName];
return checklist != null ? checklist.GetItems() : EmptyItemArray;
}
}
}

IEnumerable type cast

{
--
public static IEnumerable<Datarow> Codes(string topvalue)
{
DataTable itemCodes = new DataTable();
itemCodes.Columns.Add("itemId");
itemCodes.Columns.Add("itemCode");
itemCodes.Rows.Add(0, firstCallingCode);
DataTable Codes = GetAllItems().Tables[0];
foreach (DataRow item in Codes.Rows)
{
if (item["ItemCode"] != DBNull.Value)
{
itemCodes.Rows.Add(item.Field<int?>("itemId"), item.Field<string>("itemCode"));
}
}
return itemCodes.AsEnumerable();d
}
how can i bind it to dropdownlist: i tried this
ddcodes.datasource = codes.getenumerable();
ddcodes.databind();
when i do this i get error about typecast. i can not solve it tried a lot please help.
my method is actually this
public static IEnumerable"Datarow" Codes(string topvalue)
dont know why editor took that datarow off. bracket and datarow.
You just need to pass in the return value from the Codes method.
ddcodes.datasource = Codes();
ddcodes.databind();
You don't need to "get" an enumerable. The Codes method is already returning one.

ASP.Net Custom Control

I am developing a custom control that needs to display a dropdownlist as a composite control.
The drop down list gets populated from a Rest web service. The problem I am facing is that the dropdownlist only has DataTextField and DataValueField but I need a way of storing more values in the control i.e. I have a couple of other properties I need to access for the selected item.
What is the best way of going about this?
Here is the code I have so far:
[ValidationProperty("SelectedValue")]
public class SelectSurveyControl : Panel
{
private DropDownList ddlSurveys;
public string SelectedSurveyId
{
get
{
return SelectedValue;
}
}
public string SelectedSurveyJavascriptEmbedCode
{
get
{
return this.ddlSurveys.SelectedItem.Attributes[""];
}
}
public string SelectedValue
{
get
{
return ddlSurveys.SelectedValue;
}
set
{
if (ddlSurveys == null)
{
ddlSurveys = new DropDownList();
}
ddlSurveys.SelectedValue = value;
}
}
protected override void OnLoad(EventArgs e)
{
base.OnInit(e);
if (ddlSurveys == null)
{
ddlSurveys = new DropDownList();
}
IList<Survey> surveys = GetSurveys();
this.ddlSurveys.DataSource = surveys;
this.ddlSurveys.DataTextField = "title";
this.ddlSurveys.DataValueField = "id";
this.ddlSurveys.DataBind();
ddlSurveys.SelectedValue = this.SelectedValue;
ddlSurveys.CssClass = "umbEditorTextFieldMultiple charlimit";
ddlSurveys.Attributes.Add("SurveyId", SelectedSurveyId);
ddlSurveys.Attributes.Add("JavascriptEmbedingCode", SelectedSurveyId);
this.Controls.Add(ddlSurveys);
}
public IList<Survey> GetSurveys()
{
...
}
}
Try using a string join/split to store and retrieve the various values, then you don't have to customize your dropdown list very much.
For Example:
Text: Some Title
Value: 1|testing test|2/12/2010
This will let you store as many values as you want, so long as you choose an appropriate character to join and split on. I usually use the bar, as in my example above.
Side Note: I was looking at your selected value set handler and it needs some tweaking. You shouldn't check for a null drop down list, instead you should call EnsureChildControls() before each get and set instead. Make sure you override the CreateChildControls() method and create your controls there.
You could use a hidden field and iterate thru a copy of the returned Surveys like this:
foreach(Survey s in Surveys){
string val = s.id + ":" + s.<property1> + ":" + s.<property2>;
hiddenField.Value += val +",";
}
When you need to read from the hidden field, you use String.Split to separate the values into arrays using ',' as the separator and in each array, you split again using ':'.
In the first split Array1[0] who be the survey id and Array1[n!=0] would be the properties of the Survey with the id = Array1[0]. Array[n!=0] would then be split into Array2.
I would suggest handling empty property values with an empty string or something or else you might end up with unequal lengths especially if you specify StringSplitOptions.RemoveEmptyEntries.
Agricfowl

Resources