Why I cannot delete properly from a List and ListView? - c#

I have a ListView in my Form.
I want to delete a row, but when I select one and delete it, later it comes back and I can't delete from the List where data comes from.
Why is that?
Pontszam pt = new Pontszam();
List<int> pontszamook = new List<int>();
List<string> nevek = new List<string>();
List<string> idk = new List<string>();
List<string> ptList = new List<string>();
int osszSor = 0;
public int sorokSzama()
{
osszSor = pt.select().Count;
return osszSor;
}
private void Ponttablazat_Load(object sender, EventArgs e)
{
osszSor = sorokSzama();
ptList = pt.select();
listScore.Items.Clear();
for (int i = 0; i < osszSor; i++)
{
string[] adatok = ptList[i].Split(';');
idk.Add(adatok[0]);
nevek.Add(adatok[1]);
pontszamook.Add(Convert.ToInt32(adatok[2]));
var row = new string[] { nevek[i], Convert.ToString(pontszamook[i]) };
ListViewItem lvi = new ListViewItem(idk[i]);
lvi.SubItems.AddRange(row);
listScore.Items.Add(lvi);
}
}
private void btnDelete_Click(object sender, EventArgs e)
{
if (listScore.SelectedItems != null)
{
for (int i = listScore.SelectedItems.Count - 1; i >= 0; i--)
{
ListViewItem itm = listScore.SelectedItems[i];
int indeX = itm.Index;
listScore.Items[itm.Index].Remove();
ptList[indeX] = null;
idk[indeX] = null;
nevek[indeX] = null;
pontszamook[indeX] = -1;
pt.deletetRow(itm.Index);
}
}
}
private void btnDelete_Click(object sender, EventArgs e) { if (listScore.SelectedItems != null) { for (int i = listScore.SelectedItems.Count - 1; i >= 0; i--) { ListViewItem itm = listScore.SelectedItems[i]; int indeX = itm.Index; listScore.Items[itm.Index].Remove(); ptList[indeX] = null; idk[indeX] = null; nevek[indeX] = null; pontszamook[indeX] = -1; pt.deletetRow(itm.Index); } } }

Related

ASP.NET - Retrieving Grid View Data when EnableViewState is Set to False

I am building an application that needs to display data in a GridView control, grouped by a particular value, and then export it to PDF.I used this set of classes here (http://www.agrinei.com/gridviewhelper/gridviewhelper_pt.htm) for grouping, and it works well. However, I had to set EnableViewState to false for it to work properly. The problem comes when I need to export it to PDF. Previously (before using GridViewHelper), this was working. However, it now generates an empty report (I suppose because EnableViewState is false).
How can I save the data and structure of the GridView produced through use of the GridViewHelper class in order to export it to PDF?
Some of my aspx (portions of code omitted for brevity)
public partial class all : System.Web.UI.Page
{
Int32 userID;
Int32 currentID;
protected void Page_Load(object sender, EventArgs e)
{
GridViewHelper helper = new GridViewHelper(allTicketGrid);
helper.RegisterGroup("propName", true, true);
helper.ApplyGroupSort();
userID = Convert.ToInt32(Session["userID"]);
if (Session["userLevel"] == null || Session["userLevel"] == "")
{
Response.Redirect("~/Default.aspx");
}
if (!IsPostBack)
{
this.populate();
}
}
protected void populate()
{
toDateBox.Text = DateTime.Now.ToShortDateString();
fromDateBox.Text = DateTime.Now.ToShortDateString();
using (ticketModel dbContext = new ticketModel())
{
END_USER user = dbContext.END_USER.First(u => u.END_USER_ID == userID);
itemCheckBoxList.DataSource = dbContext.ITEM_TYPE.ToList();
itemCheckBoxList.DataTextField = "DESCRIPTION";
itemCheckBoxList.DataValueField = "ITEM_TYPE_ID";
itemCheckBoxList.DataBind();
List<Int32> propIDList = new List<Int32>();
foreach(END_USER_PROPERTY item in user.END_USER_PROPERTY.ToList() ) {
propIDList.Add((Int32)item.PROPERTY_ID);
}
locationCheckBoxList.DataSource = dbContext.PROPERTies.Where(p=> propIDList.Contains(p.PROPERTY_ID)).ToList();
locationCheckBoxList.DataTextField = "SHORT_NAME";
locationCheckBoxList.DataValueField = "PROPERTY_ID";
locationCheckBoxList.DataBind();
}
}
protected void exportReport(object sender, EventArgs e)
{
DataTable dt = new DataTable();
for (int i = 0; i < allTicketGrid.Columns.Count; i++)
{
dt.Columns.Add(allTicketGrid.Columns[i].HeaderText);
}
foreach (GridViewRow rowView in allTicketGrid.Rows)
{
DataRow dr = dt.NewRow();
for (int i = 0; i < rowView.Cells.Count; i++)
{
dr[i] = rowView.Cells[i].Text.Trim();
}
dt.Rows.Add(dr);
}
Document doc = pdfWorker.readyDocument();
pdfWorker.createTable(doc, dt);
String filePath = Server.MapPath("~/reports/files/");
String fileName = "report_" + DateTime.Now.ToString("MM-dd-yyyy") + ".pdf";
filePath += fileName;
pdfWorker.savePDF(doc, filePath);
Response.ContentType = "application/pdf";
Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
Response.TransmitFile(filePath);
Response.End();
}
protected void generateReport(object sender, EventArgs e)
{
int[] selectedLocations = getLocations();
int[] selectedItemTypes = getItems();
DateTime from = Convert.ToDateTime(fromDateBox.Text);
DateTime to = Convert.ToDateTime(toDateBox.Text);
if (!allButton.Checked)
{
Int32 statusID;
if (openButton.Checked)
{
statusID = 1;
}
else
{
statusID = 2;
}
using (ticketModel dbContext = new ticketModel())
{
allTicketGrid.DataSource = dbContext.TICKETs.Where(t => t.STATUS_TYPE.STATUS_TYPE_ID == statusID && selectedLocations.Contains(t.PROPERTY_ID) && selectedItemTypes.Contains(t.ITEM_TYPE_ID) && t.OPEN_STATUS.UPDATED_DATE >= from && t.OPEN_STATUS.UPDATED_DATE <= to).ToList();
allTicketGrid.DataBind();
}
}
else
{
using (ticketModel dbContext = new ticketModel())
{
allTicketGrid.DataSource = dbContext.TICKETs.Where(t => selectedLocations.Contains(t.PROPERTY_ID) && selectedItemTypes.Contains(t.ITEM_TYPE_ID) && t.OPEN_STATUS.UPDATED_DATE >= from && t.OPEN_STATUS.UPDATED_DATE <= to).ToList();
allTicketGrid.DataBind();
}
}
}
and my pdfWorker class:
static class pdfWorker
{
public static Document readyDocument() {
Document doc = new Document();
Section section = doc.AddSection();
Style docStyles = doc.Styles["Normal"];
docStyles.Document.DefaultPageSetup.Orientation = MigraDoc.DocumentObjectModel.Orientation.Landscape;
docStyles.Font.Size = 8;
docStyles.ParagraphFormat.FirstLineIndent = 0;
return doc;
}
public static void createTable(Document document, DataTable dataTable)
{
Table table = new Table();
table.Format.Font.Size = 6;
table.BottomPadding = 10;
int colCount = dataTable.Columns.Count;
Row pdfRow;
Cell pdfCell;
for (int i = 0; i < colCount; i++)
{
table.AddColumn();
}
pdfRow = table.AddRow();
for (int i = 0; i < colCount; i++)
{
pdfCell = pdfRow.Cells[i];
pdfCell.Row.Format.Font.Size = 10;
pdfCell.AddParagraph(dataTable.Columns[i].ToString());
}
foreach (DataRow row in dataTable.Rows)
{
pdfRow = table.AddRow();
pdfRow.HeightRule = RowHeightRule.AtLeast;
for (int i = 0; i < colCount; i++)
{
pdfCell = pdfRow.Cells[i];
pdfCell.AddParagraph(row[i].ToString());
}
}
document.LastSection.Add(table);
}
public static void savePDF(Document doc, String fileName) {
PdfDocumentRenderer renderer = new PdfDocumentRenderer(true, PdfSharp.Pdf.PdfFontEmbedding.Always);
SaveFileDialog saveDialog = new SaveFileDialog();
renderer.Document = doc;
renderer.RenderDocument();
renderer.PdfDocument.Save(fileName);
}
}
}
Thanks so much for any help.
You can put the code that populates the GridView in a separate method:
protected void generateReport(object sender, EventArgs e)
{
BindReportData();
}
private void BindReportData()
{
int[] selectedLocations = getLocations();
int[] selectedItemTypes = getItems();
DateTime from = Convert.ToDateTime(fromDateBox.Text);
DateTime to = Convert.ToDateTime(toDateBox.Text);
if (!allButton.Checked)
{
Int32 statusID;
if (openButton.Checked)
{
statusID = 1;
}
else
{
statusID = 2;
}
using (ticketModel dbContext = new ticketModel())
{
allTicketGrid.DataSource = dbContext.TICKETs.Where(t => t.STATUS_TYPE.STATUS_TYPE_ID == statusID && selectedLocations.Contains(t.PROPERTY_ID) && selectedItemTypes.Contains(t.ITEM_TYPE_ID) && t.OPEN_STATUS.UPDATED_DATE >= from && t.OPEN_STATUS.UPDATED_DATE <= to).ToList();
allTicketGrid.DataBind();
}
}
else
{
using (ticketModel dbContext = new ticketModel())
{
allTicketGrid.DataSource = dbContext.TICKETs.Where(t => selectedLocations.Contains(t.PROPERTY_ID) && selectedItemTypes.Contains(t.ITEM_TYPE_ID) && t.OPEN_STATUS.UPDATED_DATE >= from && t.OPEN_STATUS.UPDATED_DATE <= to).ToList();
allTicketGrid.DataBind();
}
}
}
And call that method at the start of exportReport:
protected void exportReport(object sender, EventArgs e)
{
BindReportData();
...
}

C# Create Tracks Parents which Depend on Children

I'm trying to create tracks of Parent that have more than a child and put theme in dynamic ListBox
i have this ParentActivity table"
tblParentActivity
and I want to make tracks depend on ParentActivity table to be in ListBox like this:
Tracks in ListBox
the code so far:
private void TrackingActivity(long ParentActivityID)
{
DataTable dtActiveChild = objA.SelectActivityChild(ParentActivityID);
ListBox lstBox = new ListBox();
lstBox.ID = "lstTrack" + ParentActivityID.ToString();
lstBox.Width = 200;
pnlTrack.Controls.Add(lstBox);
for (int i = 0; i < dtActiveChild.Rows.Count; i++)
{
long ActivityChildID = Convert.ToInt64(dtActiveChild.Rows[i]["ActivityID"].ToString());
string ActivityChildName = dtActiveChild.Rows[i]["ActivityName"].ToString();
lstBox.Items.Add(new ListItem (ActivityChildName.ToString(),ActivityChildID.ToString()));
DataTable dtBrotherActivity = objA.selectBrotherActivity(ActivityChildID);
if (dtBrotherActivity.Rows.Count > 0)
{
TrackingActivity(ActivityChildID);
}
}
}
for example ParentActivityID=1;
selectBrotherActivity is query to get another child of it parent
it gave me distribution like this:
|1|2 3|4 5|7|9|10|7|9|10|6|8|9|10|
which || means ListBox
Ok thanks to everyone I found it:
protected void btnCreateTrack_Click(object sender, EventArgs e)
{
ListBox lstBoxParent = new ListBox();
lstBoxParent.ID = "lstTrack1";
lstBoxParent.Width = 200;
lstBoxParent.Height = 200;
pnlTrack.Controls.Add(lstBoxParent);
TrackingActivity(1, lstBoxParent );
}
private void TrackingActivity(long ParentActivityID, ListBox lstBoxParent)
{
chk:
DataTable dtActiveChild = objWFAI.SelectActivityChild(ParentActivityID);
string ActivityName = objWFA.CurrentActivityName(ParentActivityID);
lstBoxParent.Items.Add(new ListItem(ActivityName, ParentActivityID.ToString()));
for (int i = dtActiveChild .Rows.Count - 1; i >= 0; i--)
{
long ActivityChildID = Convert.ToInt64(dtActiveChild .Rows[i][" ActivityID"].ToString());
if (i != 0)
{
ListBox lstBoxChild = new ListBox();
lstBoxChild.ID = "lstTrack" + ActivityChildID.ToString();
lstBoxChild.Width = 200;
lstBoxChild.Height = 200;
pnlTrack.Controls.Add(lstBoxChild);
for (int p = 0; p < lstBoxParent.Items.Count; p++)
{
lstBoxChild.Items.Add(new ListItem(lstBoxParent.Items[p].Text, lstBoxParent.Items[p].Value));
}
TrackingActivity(ActivityChildID, lstBoxChild);
}
else
{
ParentActivityID = ActivityChildID ;
goto chk;
}
}

GridView missing data between postbacks

So basically I am doing a manage packaging item system. The scenario is, when I select from gvSPU, gvFinalised should display the item in database. After that, when I add new item into the gvFinalised, it supposed to keep stacking up the items instead of wiping out the previous record and display the added latest one. Here is the code:
private List<DistributionStandardPackingUnitItems> tempDistSPUI
{
get
{
if (ViewState["tempDistSPUI"] == null)
{
return new List<DistributionStandardPackingUnitItems>();
}
else
{
return (List<DistributionStandardPackingUnitItems>)ViewState["tempDistSPUI"];
}
}
set
{
ViewState["tempDistSPUI"] = value;
}
}
protected void gvSPU_OnRowCommand(object sender, GridViewCommandEventArgs e)
{
int packagesNeeded = prodPackBLL.getPackagesNeededByDistributionID(distributionID);
int rowNo = int.Parse(e.CommandArgument.ToString());
SPUname = this.gvSPU.DataKeys[rowNo].Value.ToString();
lblSPUname.Text = SPUname;
List<DistributionStandardPackingUnitItems> templist = new List<DistributionStandardPackingUnitItems>();
templist = tempDistSPUI;
templist = packBLL.getAllDistSPUItemByDistributionIDnSPUName(distributionID, SPUname);
gvFinalised.DataSource = templist;
gvFinalised.DataBind();
this.tempDistSPUI = templist;
}
When gvSPU row is selected, it should store all the records into templist and display in gvFinalised.
List<string> prodVariantIDList = new List<string>();
private List<string> SelectedVariantDetailIDs
{
get
{
if (ViewState["SelectedVariantDetailIDs"] == null)
{
return new List<string>();
}
else
{
return (List<string>)ViewState["SelectedVariantDetailIDs"];
}
}
set
{
ViewState["SelectedVariantDetailIDs"] = value;
}
}
protected void lbnAdd_Click(object sender, EventArgs e)
{
List<ProductPacking> prodVariantDetail = new List<ProductPacking>();
int packagesNeeded = prodPackBLL.getPackagesNeededByDistributionID(distributionID);
// get the last product variant IDs from ViewState
prodVariantIDList = this.SelectedVariantDetailIDs;
foreach (RepeaterItem ri in Repeater1.Items)
{
GridView gvProduct = (GridView)ri.FindControl("gvProduct");
foreach (GridViewRow gr in gvProduct.Rows)
{
CheckBox cb = (CheckBox)gr.FindControl("cbCheckRow");
//Prevent gvFinalised to store duplicate products
if (cb.Checked && !prodVariantIDList.Any(i => i == gvProduct.DataKeys[gr.RowIndex].Value.ToString()))
{
// add the corresponding DataKey to idList
prodVariantIDList.Add(gvProduct.DataKeys[gr.RowIndex].Value.ToString());
}
}
}
for (int i = 0; i < prodVariantIDList.Count; i++)
{
prodVariantDetail.Add(prodPackBLL.getProdVariantDetailByID(prodVariantIDList[i]));
}
gvFinalised.DataSource = prodVariantDetail;
gvFinalised.DataBind();
// save prodVariantIDList to ViewState
this.SelectedVariantDetailIDs = prodVariantIDList;
}
When add button is on click, it should append with the record in gridview instead of wiping them off and insert the checked one.
I am using the viewState to store the record between postbacks. However, when I try to add new item into gvFinalised, the previous record which in the templist will disappear and the gvFinalised will be populated with the result from prodVariantDetail list.
Any guide? Thanks in advance.
EDIT
List<DistributionStandardPackingUnitItems> itemList = new List<DistributionStandardPackingUnitItems>();
protected void gvSPU_OnRowCommand(object sender, GridViewCommandEventArgs e)
{
int packagesNeeded = prodPackBLL.getPackagesNeededByDistributionID(distributionID);
int rowNo = int.Parse(e.CommandArgument.ToString());
SPUname = this.gvSPU.DataKeys[rowNo].Value.ToString();
lblSPUname.Text = SPUname;
itemList = tempDistSPUI;
itemList = packBLL.getAllDistSPUItemByDistributionIDnSPUName(distributionID, SPUname);
gvFinalised.DataSource = itemList;
gvFinalised.DataBind();
this.tempDistSPUI = itemList;
}
protected void lbnAdd_Click(object sender, EventArgs e)
{
List<DistributionStandardPackingUnitItems> prodVariantDetail = new List<DistributionStandardPackingUnitItems>();
int packagesNeeded = prodPackBLL.getPackagesNeededByDistributionID(distributionID);
// get the last product variant IDs from ViewState
prodVariantIDList = this.SelectedVariantDetailIDs;
foreach (RepeaterItem ri in Repeater1.Items)
{
GridView gvProduct = (GridView)ri.FindControl("gvProduct");
foreach (GridViewRow gr in gvProduct.Rows)
{
CheckBox cb = (CheckBox)gr.FindControl("cbCheckRow");
//Prevent gvFinalised to store duplicate products
if (cb.Checked && !prodVariantIDList.Any(i => i == gvProduct.DataKeys[gr.RowIndex].Value.ToString()))
{
// add the corresponding DataKey to idList
prodVariantIDList.Add(gvProduct.DataKeys[gr.RowIndex].Value.ToString());
}
}
}
for (int i = 0; i < prodVariantIDList.Count; i++)
{
prodVariantDetail.Add(packBLL.getProdVariantDetailByID(prodVariantIDList[i]));
}
for (int j = 0; j < itemList.Count; j++)
{
prodVariantDetail.Add(itemList[j]);
}
gvFinalised.DataSource = prodVariantDetail;
gvFinalised.DataBind();
}
// save prodVariantIDList to ViewState
this.SelectedVariantDetailIDs = prodVariantIDList;
}
You have to add the elements of tempDistSPUI into prodVariantDetail before binding prodVariantDetail to gvFinalised.
Here's what I would do using List.AddRange Method:
protected void lbnAdd_Click(object sender, EventArgs e)
{
List<DistributionStandardPackingUnitItems> prodVariantDetail = new List<DistributionStandardPackingUnitItems>();
int packagesNeeded = prodPackBLL.getPackagesNeededByDistributionID(distributionID);
// get the last product variant IDs from ViewState
prodVariantIDList = this.SelectedVariantDetailIDs;
foreach (RepeaterItem ri in Repeater1.Items)
{
GridView gvProduct = (GridView)ri.FindControl("gvProduct");
foreach (GridViewRow gr in gvProduct.Rows)
{
CheckBox cb = (CheckBox)gr.FindControl("cbCheckRow");
//Prevent gvFinalised to store duplicate products
if (cb.Checked && !prodVariantIDList.Any(i => i == gvProduct.DataKeys[gr.RowIndex].Value.ToString()))
{
// add the corresponding DataKey to idList
prodVariantIDList.Add(gvProduct.DataKeys[gr.RowIndex].Value.ToString());
}
}
}
for (int i = 0; i < prodVariantIDList.Count; i++)
{
prodVariantDetail.Add(packBLL.getProdVariantDetailByID(prodVariantIDList[i]));
}
// get the content of tempDistSPUI from ViewState
itemList = this.tempDistSPUI;
// add all elements of itemList to prodVariantDetail
prodVariantDetail.AddRange(itemList);
gvFinalised.DataSource = prodVariantDetail;
gvFinalised.DataBind();
// save prodVariantIDList to ViewState
this.SelectedVariantDetailIDs = prodVariantIDList;
}

How to store name of dynamic checkbox in an String array

How can store name of dynamically created checkbox in a String array when I don't know how many checkbox will user select at runtime.
Say I have 10 dynamic checkboxes and out of 10 user select 6 checkboxes randomly now how can get the name of those selected checkboxes and store them in a String array.
I know how to use event handler on dynamic check box but confused how to declare Straing array when I don't know what will be be size of an array.
Here what I have done till now -
private void CheckBoxCheckedChanged(object sender, EventArgs e)
{
CheckBox c = (CheckBox)sender;
//Label myLabel;
String str = null;
if (c.Checked == true)
{
str = c.Text;
gpBox[gpcount] = new GroupBox();
gpBox[gpcount].Name = "gpBox" + Convert.ToString(count);
gpBox[gpcount].Text = str;
gpBox[gpcount].Location = new Point(5, gpposition);
gpBox[gpcount].AutoSize = true;
this.Controls.Add(gpBox[gpcount]);
aCommand3 = new OleDbCommand("select * from batch_tbl where batch_branch LIKE '" + str + "'", main_connection);
aAdapter3 = new OleDbDataAdapter(aCommand3);
ds3 = new DataSet();
aAdapter3.Fill(ds3, "app_info");
ds3.Tables[0].Constraints.Add("pk_bno", ds3.Tables[0].Columns[0], true);
int batch_count = ds3.Tables[0].Rows.Count;
batchCheckBox = new CheckBox[batch_count];
//filling the groupbox with batch code by generating dynamic checkboxes
for (int j=0; j < batch_count; ++j)
{
batchCheckBox[j] = new CheckBox();
batchCheckBox[j].Name = "batch" + Convert.ToString(k);
batchCheckBox[j].Text = ds3.Tables[0].Rows[j][1].ToString();
Console.WriteLine(batchCheckBox[j].Text);
batchCheckBox[j].Location = new System.Drawing.Point(104 * position, 30);
gpBox[gpcount].Controls.Add(batchCheckBox[j]);
batchCheckBox[j].CheckStateChanged += new System.EventHandler(BatchBoxCheckedChanged);
position++;
count++;
Console.WriteLine(batchCheckBox[j].Name);
k++;
}
position = 1;
gpposition += 100;
}
else
{
count--;
this.Controls.RemoveByKey("lbl" + c.Name);
this.Update();
}
}
int total_batch = 1;
string[] batchname;
private void BatchBoxCheckedChanged(object sender, EventArgs e)
{
CheckBox batchBox = (CheckBox)sender;
//Here I want to store name of checkbox in array
if (batchBox.Checked == true)
{
batchname = new String[total_batch];
total_batch++;
}
else
{
}
}
You can try this:
//Gets all checkbox's on the form
List<CheckBox> chks = Controls.OfType<CheckBox>().ToList();
//take only those who is checked, and select only their name property
List<string> names = chks.Where(c => c.Checked).Select(c => c.Name).ToList();
UPDATE
For testing you could print a list of the selected names:
string txt = "";
foreach(string name in names)
{
txt += name+" \n\r";
}
MessageBox.Show(txt);
Thank you everbody
}
list = new List<string>();
}
private void BatchBoxCheckedChanged(object sender, EventArgs e)
{
CheckBox batchBox = (CheckBox)sender;
//Here I want to store name of checkbox in array
if (batchBox.Checked == true)
{
list.Add(batchBox.Text);
}
}
private void button1_Click(object sender, EventArgs e)
{
foreach(string prime in list) // Loop through List with foreach
{
Console.WriteLine(prime);
}
}
This is Done

List: Insert new item after the currently pointed to item

I am currently working/experimenting with lists. I am able to determine with function GetNextTree the position of each item in my list such as: First, Next and Last. I have an already made list from an array ax but now I am trying to implement an insert button that will take values tree_type, tree_height, tree_price, tree_instock and create the item. Since I can point anywhere in my list, the insert will be intended to add an item after the currently pointed to item. That is where my question is: How can I add a new item after the currently pointed to item?
public class fruit_trees
{
private string tree_type = " ";
private int tree_height = 0;
public double tree_price = 0;
private int tree_instock = 0;
public fruit_trees next_tree;
public fruit_trees(string newtree, int newheight, double newprice, int newinstock)
{
tree_type = newtree;
tree_height = newheight;
tree_price = newprice;
tree_instock = newinstock;
next_tree = null;
}
public string GetTreeType
{
get { return tree_type;
}
}
public override string ToString()
{
return tree_type + " " + tree_height + " " + tree_price + " " + tree_instock;
}
}
public class ListForTrees
{
private fruit_trees first_tree;
public fruit_trees First_tree
{
get
{
return first_tree;
}
}
public fruit_trees last_tree;
public int current;
public int count = 0;
public ListForTrees(fruit_trees new_tree)
{
first_tree = new_tree;
last_tree = new_tree;
count = 1;
current = 0;
}
public ListForTrees(IEnumerable trees)
{
current = 0;
foreach (fruit_trees t in trees)
{
this.AddTree(t);
}
}
public fruit_trees GetNextTree()
{
//current = 0;
fruit_trees ft = first_tree;
if (current == count)
{
current = 0;
}
int i = 0;
while (i != current)
{
ft = ft.next_tree;
i++;
}
return ft;
}
}
ListForTrees mainlist = new ListForTrees();
private void BtnInsertTree_Click(object sender, EventArgs e)
{
try
{
int height = Convert.ToInt32(TxtTreeHeight.Text);
int stock = Convert.ToInt32(TxtTreeStock.Text);
double price = Convert.ToDouble(TxtTreePrice.Text);
fruit_trees treeadd = new fruit_trees(TxtTreeName.Text, height, price, stock);
mainlist.AddTree(treeadd);
}
catch
{
MessageBox.Show("Please check intput fields");
}
}
private void BtnGo_Click(object sender, EventArgs e)
{
fruit_trees[] ax = { new fruit_trees("cherry", 48, 12.95, 3),
new fruit_trees("pine", 36, 9.95, 8),
new fruit_trees("oak", 60, 14.95, 2),
new fruit_trees("peach", 54, 19.95, 3),
new fruit_trees("pear", 36, 11.85, 2),
new fruit_trees("apple", 62, 13.45, 5)
};
mainlist = new ListForTrees(ax);
fruit_trees current = mainlist.First_tree;
while (current != null)
{
TxtOutput.AppendText(current.ToString() + Environment.NewLine);
current = current.next_tree;
}
}
private void ShowFirstItem_Click(object sender, EventArgs e)
{
//Show Next Item
labelSpecificTree.Text = mainlist.First_tree.GetTreeType;
}
private void ShowNextItem_Click(object sender, EventArgs e)
{
fruit_trees obj = mainlist.GetNextTree();
if (obj.next_tree == null)
{
labelSpecificTree.Text = mainlist.First_tree.GetTreeType.ToString();
}
else
{
mainlist.current++;
labelSpecificTree.Text = obj.next_tree.GetTreeType.ToString();
}
}
private void ShowLastItem_Click(object sender, EventArgs e)
{
// Show First Item
labelSpecificTree.Text = mainlist.last_tree.GetTreeType;
}
So I'm slightly confused by what's going on here. You're implementing your own ArrayList like class which is not really a list at all... I don't really see the point of doing such things in C# but alright... Here's the method;
fruit_trees[] InsertNode(fruit_trees current, fruit_trees nNode)
{
fruit_trees[] temp = new fruit_trees[ax.Length + 1];
int i = 0;
while (ax[i] != current)
{
temp[i] = ax[i];
i++;
}
temp[i+1] = nNode;
while (i < ax.Length)
{
temp[i+1] = ax[i];
}
return temp;
}
call this like such;
ax = InsertNode(current, nNode);
What we're doing is making a new list with one extra slot, copying each fruit_tree over til we hit the node we want to insert after, then we copy the new tree in. After that we copy over the rest of the old array. Then we return the new array.

Categories