I want to implement stack in my program by Genericx. I have a textbox and button to add elements in stack, a dropdownlist box and a button to bind total stack in dropdownlist box.
I have generic class and the code is below:
[Serializable]
public class myGenClass<T>
{
private T[] _el开发者_JS百科ements;
private int _pointer;
public myGenClass(int size)
{
_elements = new T[size];
_pointer = 0;
}
public void Push(T item)
{
if (_pointer > _elements.Length - 1)
{
throw new Exception("Stack is full");
}
_elements[_pointer] = item;
_pointer++;
}
public T Pop()
{
_pointer--;
if (_pointer < 0)
{
throw new Exception("Stack is empty");
}
return _elements[_pointer];
}
public T[] myBind()
{
T[] showall = new T[_pointer];
Array.Copy(_elements,showall, _pointer);
T[] newarray = showall;
Array.Reverse(showall);
return showall;
}
}
and my .cs page is below:
public partial class _Default : System.Web.UI.Page
{
myGenClass<int> mystack = new myGenClass<int>(25);
protected void Button1_Click(object sender, EventArgs e)
{
mystack.Push(Int32.Parse(TextBox1.Text));
//DropDownList1.Items.Add(mystack.Pop().ToString());
TextBox1.Text = string.Empty;
TextBox1.Focus();
}
protected void Button2_Click(object sender, EventArgs e)
{
//string[] db;
//db = Array.ConvertAll<int, string>(mystack.myBind(), Convert.ToString);
DropDownList1.DataSource = mystack.myBind();
DropDownList1.DataBind();
}
}
but when I bind the datasource property of dropdownlist box to generic type return array (i.e. myBind()), it shows empty... Please help..
I haven't looked at the myGenClass type, but are you persisting the instance of myGenClass between requests? Each button click would post to a new instance of the _default class which initializes with an empty stack. If the stack isn't persisted between requests, it will contain its default values.
精彩评论