IEnumerable type cast - asp.net

{
--
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.

Related

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.

how to update the values while iterating dictionary items?

I have a dictionary:
Dictionary<string, long> Reps = new Dictionary<string, long>();
and I want to update the values while iterating through all items, like this:
foreach (string key in Reps.keys)
{
Reps[key] = 0;
}
it is giving me an error saying:
"Collection was modified; enumeration operation may not execute"
can anyone tell me why it is giving me this error, because I have one more function that adds the value, and it is called when button is clicked:
public static void Increment(string RepId, int amount)
{
long _value = Convert.ToInt64(Reps[RepId]);
_value = _value + amount;
Reps[RepId] = _value;
}
and this function is working fine. so whats the problem when updating all the values? And whats the solution for this?
more simplified, do this:
foreach (string key in Reps.keys.ToList())
{
Reps[key] = 0;
}
and the reason for the error is you are trying to edit the actual object which is in use and if you make a copy of it and then use it like this:
var repscopy = Reps;
foreach (string key in repscopy.keys)
{
Reps[key] = 0;
}
it'll give the same error as it also pointing to the original object, and when the ToList() is added it created a new object of List
The problem is no updating the values, you just cannot change the collection that your foreach() is based on while the foreach is being iterated.
Try somehting like this
List<string> keylist = Reps.keys.ToList();
foreach(string r in keylist)
{
Reps[r] = 0;
}
this would work.
This happens because you are changing the element in the Dictionary<string, long> while looping over it with foreach. Try this.
foreach (string key in Reps.Keys.ToList())
{
Reps[key] = 0;
}
Now you are looping over a list created from the dictionarys key. As it is not the original collection thats modified, the error will go away.

how do i convert IEnumerable<MyClass> to DataTable very fast?

I'm familiar with the reflection method that converts any IEnumerable to DataTable, but it's very very slow!
When i get not huge but big chunk of data i get very slow browser reaction, because it's very complicated data to handle.
I need to boost my prefformance, how do i do it?
PS: Checked LazyLoading DataTable no success there ether, maybe someone will show me how to do it?
Thank you very very much in advance.
See this artice for detailed explanation.
Core code sample
public static DataTable ToDataTable<T>(this IEnumerable<T> collection)
{
DataTable dt = new DataTable();
Type t = typeof(T);
PropertyInfo[] pia = t.GetProperties();
//Create the columns in the DataTable
foreach (PropertyInfo pi in pia)
{
if ((pi.PropertyType.IsGenericType) )
{
Type typeOfColumn = pi.PropertyType.GetGenericArguments()[0];
dt.Columns.Add(pi.Name, typeOfColumn);
}
else
dt.Columns.Add(pi.Name, pi.PropertyType);
}
//Populate the table
foreach (T item in collection)
{
DataRow dr = dt.NewRow();
dr.BeginEdit();
foreach (PropertyInfo pi in pia)
{
dr[pi.Name] = pi.GetValue(item, null);
}
dr.EndEdit();
dt.Rows.Add(dr);
}
return dt;
}
}
Why do you think that data converting slows your app? Did your profile it?

Bind a DropDownList to IEnumerable

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();
}

Databinding to a sub object declarative syntax?

What is the format for databinding to a complex "object"? I have a linq to sql class that has containment, i.e object.containedobject.
I want to reference the sub objects fields declarative.
So I've tried my MySubField.MyBasicProperty and that did not work, as well as, MySubField_MyBasicProperty.
Thanks for any help!
I found my answer, it is a problem with boundfield class and not databinding.
http://www.iridescence.no/post/FixingBoundFieldSupportforCompositeObjects.aspx
I found solution and sharing for anyone who comes after me in the future.
You need to override the objectdatasource updating method to replace the param names. This is only possible if the objectypename property of the objectdatasource is not set or else they will be read only.
Here is my example:
protected void ObjectDataSource1_Updating(object sender, ObjectDataSourceMethodEventArgs e)
{
foreach (string currentKey in e.InputParameters.Keys)
{
if (currentKey.Contains("."))
{
string newKey = currentKey.Replace(".", "_");
object myValue = null;
if (e.InputParameters[currentKey] != null)
myValue = e.InputParameters[newKey];
if (e.InputParameters.Contains(newKey))
e.InputParameters.Remove(newKey);
e.InputParameters.Add(newKey, myValue);
e.InputParameters.Remove(currentKey);
}
}

Resources