Use Multiple ASP.NET controls with the same ID - c#

I am trying to dynamically add controls to an asp.net page. The page is rendering correctly but after posting back, I get the following error:
[HttpException (0x80004005): Multiple controls with the same
ID 'ParentTextBox_ChildTextBox_TV_PostRender' were found. FindControl requires that controls have unique IDs.]
System.Web.UI.Control.FillNamedControlsTable(Control namingContainer, ControlCollection controls) +273
System.Web.UI.Control.EnsureNamedControlsTable() +61
System.Web.UI.Control.FindControl(String id, Int32 pathOffset) +222
System.Web.UI.Control.FindControl(String id, Int32 pathOffset) +327
System.Web.UI.Page.FindControl(String id) +38
System.Web.UI.Page.ProcessPostData(NameValueCollection postData, Boolean fBeforeLoad) +232
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1434
I have tried several different things a none of which work. I thought removing the control in OnInit or on page_load like this
Control c = Page.FindControl("ParentTextBox_ChildTextBox_TV_PostRender");
Page.Controls.Remove(c);
will work but it doesn't
Code of custom tree view control
// file ContainerTreeView.cs
using System.Web.UI;
using System.Web.UI.WebControls;
using System;
namespace DASHBOARD
{
[ToolboxData("<{0}:ContainerTreeView runat=server></{0}:ContainerTreeView>")]
public class ContainerTreeView : TreeView, INamingContainer
{
public ContainerTreeView()
: base()
{
PathSeparator = ClientIDSeparator;
}
protected override void OnInit(EventArgs e)
{
// Initialize Child Controls
RecurseUpdateNodes(Nodes);
base.OnInit(e);
}
protected const String s_strNodeValueSeparator = "_TV_";
protected virtual void RecurseUpdateNodes(TreeNodeCollection parrNodes)
{
if (parrNodes == null || parrNodes.Count == 0)
return;
foreach (TreeNode pNode in parrNodes)
{
ContainerTreeNode pContainerNode = pNode as ContainerTreeNode;
if (pContainerNode != null)
{
// update node pre / post rendering control IDs id
if (pContainerNode.PreRenderContainer != null)
{
pContainerNode.PreRenderContainer.ID = pContainerNode.PreRenderContainer.ID.Insert(0, pNode.ValuePath + s_strNodeValueSeparator);
Controls.Add(pContainerNode.PreRenderContainer);
}
if (pContainerNode.PostRenderContainer != null)
{
pContainerNode.PostRenderContainer.ID = pContainerNode.PostRenderContainer.ID.Insert(0, pNode.ValuePath + s_strNodeValueSeparator);
Controls.Add(pContainerNode.PostRenderContainer);
}
}
// update children
RecurseUpdateNodes(pNode.ChildNodes);
}
}
public ContainerTreeNode CreateTreeNode()
{
return new ContainerTreeNode(this, false);
}
protected override TreeNode CreateNode()
{
return CreateTreeNode();
}
// collection of child controls
protected override ControlCollection CreateControlCollection()
{
return new ControlCollection(this);
}
protected override void RenderChildren(HtmlTextWriter writer)
{
// do not render children as they will be rendered within treeview nodes
// base.RenderChildren(writer);
}
}
}
This is the page where I am adding the tree:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
namespace DASHBOARD
{
public partial class testTreeEdit : System.Web.UI.Page
{
ContainerTreeView m_pTreeView = null;
protected override void OnInit(EventArgs e)
{
Control c = Page.FindControl("ParentTextBox_ChildTextBox_TV_PostRender");
Page.Controls.Remove(c);
tb.Text += "Removed Control";
base.OnInit(e);
}
#region main
protected void Page_Load(object sender, EventArgs e)
{
if (CheckBox1.Checked)
{
renderEditTree();
}
else
{
makeTree();
TreeView1.ExpandAll();
}
}
#endregion
#region editableTreeView
/** //function to render editable tree view
protected void renderEditTree()
{
m_pTreeView = new ContainerTreeView();
ContainerTreeNode pNodeParent = m_pTreeView.CreateTreeNode();
pNodeParent.Value = "Parent";
pNodeParent.Text = "Parent";
pNodeParent.Expanded = true;
m_pTreeView.Nodes.Add(pNodeParent);
/**ContainerTreeNode pNodeChildDropDown = m_pTreeView.CreateTreeNode();
pNodeChildDropDown.Value = "ChildDropDown";
pNodeChildDropDown.Text = String.Empty;
DropDownList pList = new DropDownList();
pList.ID = "ID_DropDown";
pList.Items.Add("AAA");
pList.Items.Add("BBB");
pList.Items.Add("CCC");
pNodeChildDropDown.PostRenderControls.Add(pList);
pNodeParent.ChildNodes.Add(pNodeChildDropDown);
/**ContainerTreeNode pNodeChildButton = m_pTreeView.CreateTreeNode();
pNodeChildButton.Value = "ChildButton";
pNodeChildButton.Text = String.Empty;
Button pButton = new Button();
pButton.ID = "ID_Button";
pButton.Text = "PostBack";
pNodeChildButton.PostRenderControls.Add(pButton);
pNodeParent.ChildNodes.Add(pNodeChildButton);
/** ContainerTreeNode pNodeChildTextBox = m_pTreeView.CreateTreeNode();
pNodeChildTextBox.Value = "ChildTextBox";
pNodeChildTextBox.Text = String.Empty;
TextBox pTextBox = new TextBox();
pTextBox.ID = "ID_TextBox";
pTextBox.Text = "Some text";
pNodeChildTextBox.PostRenderControls.Add(pTextBox);
pNodeParent.ChildNodes.Add(pNodeChildTextBox);
this.treeViewContainer.Controls.Add(m_pTreeView);
}*/
//load XML file and use it to make the tree view
public void renderEditTree()
{
m_pTreeView = new ContainerTreeView();
XDocument document = XDocument.Load(Server.MapPath("~/Releases_files/releases.xml"));
foreach (XElement element in document.Descendants("Release"))
{
XName name0 = "version";
XAttribute a0 = element.Attribute(name0);
string temp0 = a0.Value;
ContainerTreeNode pmTextBox = m_pTreeView.CreateTreeNode();
pmTextBox.Value = "ParentTextBox";
pmTextBox.Text = String.Empty;
TextBox pTextBox = new TextBox();
pTextBox.ID = temp0;
pTextBox.Text = temp0;
pmTextBox.PostRenderControls.Add(pTextBox);
m_pTreeView.Nodes.Add(pmTextBox);
//n0.Text = temp0;
//TreeView1.Nodes.Add(n0);
foreach (XElement myElement in element.Descendants("Feature"))
{
XName name = "Name";
XAttribute a = myElement.Attribute(name);
string temp = a.Value;
ContainerTreeNode pcTextBox = m_pTreeView.CreateTreeNode();
pcTextBox.Value = "ChildTextBox";
pcTextBox.Text = String.Empty;
TextBox p2TextBox = new TextBox();
p2TextBox.ID = temp;
p2TextBox.Text = temp;
pcTextBox.PostRenderControls.Add(p2TextBox);
pmTextBox.ChildNodes.Add(pcTextBox);
}
this.treeViewContainer.Controls.Add(m_pTreeView);
}
}
#endregion
#region simpleTreeView
//old code
//load XML file and use it to make the tree view
public void makeTree()
{
TreeView1.Nodes.Clear();
XDocument document = XDocument.Load(Server.MapPath("~/Releases_files/releases.xml"));
foreach (XElement element in document.Descendants("Release"))
{
TreeNode n0 = new TreeNode();
XName name0 = "version";
XAttribute a0 = element.Attribute(name0);
string temp0 = a0.Value;
n0.Text = temp0;
TreeView1.Nodes.Add(n0);
foreach (XElement myElement in element.Descendants("Feature"))
{
TreeNode n = new TreeNode();
XName name = "Name";
XAttribute a = myElement.Attribute(name);
string temp = a.Value;
n.Text = temp;
n0.ChildNodes.Add(n);
}
}
}
//action to do when selected node is changed
protected void TreeView1_SelectedNodeChanged(object sender, EventArgs e)
{
XDocument document = XDocument.Load(Server.MapPath("~/Releases_files/releases.xml"));
//debug
//Label1.Text = TreeView1.SelectedNode.Text;
//Label5.Text = Convert.ToString(TreeView1.SelectedNode.Depth);
//case1: feature selected
if (TreeView1.SelectedNode.Depth > 0)
{
string featureName = TreeView1.SelectedNode.Text;
string releaseName = TreeView1.SelectedNode.Parent.Text;
foreach (XElement element in document.Descendants("Release"))
{
//find the right release in XML
XName name = "version";
XAttribute a = element.Attribute(name);
string versionAttribute = a.Value;
if (releaseName.Equals(versionAttribute))
{
foreach (XElement myElement in element.Descendants("Feature"))
{
//find the right feature in XML
XName name1 = "Name";
XAttribute a1 = myElement.Attribute(name1);
string versionAttribute1 = a1.Value;
if (featureName.Equals(versionAttribute1))
{
//found the right node, now populate the Fields
IEnumerable<XElement> dates = element.Descendants("Date");
XElement date = dates.First<XElement>();
Label5.Text = date.Value;
IEnumerable<XElement> statuses = element.Descendants("Status");
XElement status = statuses.First<XElement>();
Label6.Text = status.Value;
IEnumerable<XElement> types = myElement.Descendants("Type");
XElement type = types.First<XElement>();
Label7.Text = type.Value;
IEnumerable<XElement> developers = myElement.Descendants("Developer");
XElement developer = developers.First<XElement>();
Label8.Text = developer.Value;
IEnumerable<XElement> details = myElement.Descendants("Detail");
XElement detail = details.First<XElement>();
tb.Text = detail.Value;
}
}
}
}
}
//case2: Release selected
else
{
string releaseName = TreeView1.SelectedNode.Text;
foreach (XElement element in document.Descendants("Release"))
{
//find the right release in XML
XName name = "version";
XAttribute a = element.Attribute(name);
string versionAttribute = a.Value;
if (releaseName.Equals(versionAttribute))
{
//found the right node, now populate the Fields
IEnumerable<XElement> dates = element.Descendants("Date");
XElement date = dates.First<XElement>();
Label5.Text = date.Value;
IEnumerable<XElement> statuses = element.Descendants("Status");
XElement status = statuses.First<XElement>();
Label7.Text = " ";
Label8.Text = " ";
tb.Text = " ";
}
}
}
}
#endregion
#region userInputs
protected void Button2_Click(object sender, EventArgs e)
{
}
//edit tree check box
protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
{
if (CheckBox1.Checked )//&& TreeView1.Visible==true)
{
TreeView1.Visible = false;
if (m_pTreeView != null)
{
m_pTreeView.Visible = true;
}
Label5.Enabled = false;
Label6.Enabled = false;
Label7.Enabled = false;
Label8.Enabled = false;
tb.Enabled = false;
}
else
{
TreeView1.Visible = true;
if (m_pTreeView != null)
{
m_pTreeView.Visible = false;
}
Label5.Enabled = true;
Label6.Enabled = true;
Label7.Enabled = true;
Label8.Enabled = true;
tb.Enabled = true;
}
}
#endregion
}
}

I may be misunderstanding the code a bit, but if the PreRenderContainer and PostRenderContainer properties implement INamingcontainer and you change their IDs, I think you might not be letting them do their job. It should automatically give you unique ids. Like ctl00, ctl01 etc...

You need to set the ID property of the control to some unique value before adding it to the page. There are a number of tricks you can use to make this work out. If you provide more code, we can provide some ideas for solutions tailored to your situation.
Edit
It looks like you've got some pretty complicated stuff going on here, so I'm not grokking it fully. However, I'd look at setting the IDs of your ContainerTreeNodes when they're instantiated, rather than during the OnInit phase. I'd also make the ContainerTreeNode architecture support a means of traversing and removing a node within itself, rather than trying to manually remove a node based on a Control ID from outside the tree.

Related

XAMDataGrid: Dragging rows within grid

I'm using the XamDataGrid v14.2 and want to add the feature of dragging and dropping rows within the datagrid.
I've looked thru the Infragistics forum posts, but most of the code samples show dragging and dropping rows from one grid to another.
Is it possible to drag and drop rows within the same grid? The effect that I want to achieve is to move the sequence of the Web Announcement row numbers.
Here is an image of how the grid looks:
I posted a sample with a behavior a few months ago on the Infragistics Forums that reorders rows that it similar to your requirement.
Relevant markup:
<igDP:XamDataGrid DataSource="{Binding Items}" IsSynchronizedWithCurrentItem="True" GroupByAreaLocation="None">
<i:Interaction.Behaviors>
<DragGrid:XamDataGridDragDropBehavior/>
</i:Interaction.Behaviors>
</igDP:XamDataGrid>
C# code for the Behavior:
using System;
using System.Collections.Generic;
using Infragistics.Windows.DataPresenter;
using System.Windows.Interactivity;
using System.Windows;
using Infragistics.DragDrop;
using System.Windows.Input;
using Infragistics.Windows;
using System.Collections;
using System.Windows.Media;
using System.Reflection;
namespace DragGrid
{
public class XamDataGridDragDropBehavior : Behavior<DataPresenterBase>
{
private DataPresenterBase dataPresenter;
protected override void OnAttached()
{
base.OnAttached();
dataPresenter = this.AssociatedObject;
EventManager.RegisterClassHandler(typeof(XamDataGrid), UIElement.MouseLeftButtonDownEvent, new MouseButtonEventHandler(XamDataGrid_MouseLeftButtonDown));
var dataPresenterStyle = new Style(typeof(DataRecordPresenter));
dataPresenterStyle.Setters.Add(new EventSetter(FrameworkElement.LoadedEvent, new RoutedEventHandler(OnRecordPresenterLoaded)));
dataPresenter.Resources.Add(typeof(DataRecordPresenter), dataPresenterStyle);
DropTarget dropTarget = new DropTarget() { IsDropTarget = true };
DragDropManager.SetDropTarget(dataPresenter, dropTarget);
}
private void OnRecordPresenterLoaded(object sender, RoutedEventArgs e)
{
var recordPresenter = sender as DataRecordPresenter;
if (DragDropManager.GetDragSource(recordPresenter) != null)
{
return;
}
var dragSource = new DragSource
{
IsDraggable = true
};
dragSource.DragStart += new System.EventHandler<DragDropStartEventArgs>(dragSource_DragStart);
dragSource.Drop += OnRecordDragDrop;
dragSource.DragTemplate = ((Window)Utilities.GetAncestorFromType(this.dataPresenter, typeof(Window), true)).Resources["dragTemplate"] as DataTemplate;
DragDropManager.SetDragSource(recordPresenter, dragSource);
}
void dragSource_DragStart(object sender, DragDropStartEventArgs e)
{
ArrayList draggedItems = new ArrayList();
List<IList> sourceList = new List<IList>();
SelectedRecordCollection selectedRecords = this.dataPresenter.SelectedItems.Records;
DataRecord lastSelectedDataRecord = null;
foreach (Record r in selectedRecords)
{
DataRecord dr = r as DataRecord;
if (dr != null)
{
lastSelectedDataRecord = dr;
draggedItems.Add(dr.DataItem);
sourceList.Add(GetSourceList(dr));
}
}
DraggingData data = new DraggingData();
data.Items = draggedItems;
data.Lists = sourceList;
if (lastSelectedDataRecord != null && lastSelectedDataRecord.ParentRecord != null)
{
data.SourceProperty = lastSelectedDataRecord.RecordManager.Field.Name;
}
e.Data = data;
}
private IList GetSourceList(DataRecord record)
{
IList retVal = null;
DataRecord parent = record.ParentDataRecord;
if (parent == null)
{
// There is no parent, use the grids list
retVal = this.dataPresenter.DataSource as IList;
}
else
{
object parentDataItem = parent.DataItem;
Type dataItemType = parentDataItem.GetType();
PropertyInfo listProperty = dataItemType.GetProperty(record.RecordManager.Field.Name);
retVal = listProperty.GetValue(parentDataItem, null) as IList;
}
return retVal;
}
private void OnRecordDragDrop(object sender, DropEventArgs dragInfo)
{
var result = VisualTreeHelper.HitTest(dragInfo.DropTarget, dragInfo.GetPosition(dragInfo.DropTarget));
var targetElement = Utilities.GetAncestorFromType(result.VisualHit, typeof(DataRecordPresenter), true) as DataRecordPresenter;
if (targetElement != null)
{
DataRecord targetRecord = targetElement.DataRecord;
IList targetList = GetSourceList(targetRecord);
object targetItem = targetRecord.DataItem;
Type targetType = targetItem.GetType();
DraggingData draggedData = dragInfo.Data as DraggingData;
if (draggedData != null)
{
IList itemsList = draggedData.Items;
object firstItem = itemsList[0];
IList<IList> listsList = draggedData.Lists;
if (!targetType.IsInstanceOfType(firstItem))
{
// the target type doesn't match the items we are dropping, get the child list from the parent if we have a property.
if (draggedData.SourceProperty != null)
{
PropertyInfo listProperty = targetType.GetProperty(draggedData.SourceProperty);
targetList = listProperty.GetValue(targetItem, null) as IList;
if (targetList != null)
{
for (int i = itemsList.Count - 1; i >= 0; i--)
{
object currentItem = itemsList[i];
int targetIndex = targetList.IndexOf(targetItem);
listsList[i].Remove(currentItem);
targetList.Add(currentItem);
}
}
}
else
{
MessageBox.Show("Can't drop here");
}
}
else
{
for (int i = itemsList.Count - 1; i >= 0; i--)
{
object currentItem = itemsList[i];
int targetIndex = targetList.IndexOf(targetItem);
listsList[i].Remove(currentItem);
targetList.Insert(targetIndex, currentItem);
}
}
}
}
}
void XamDataGrid_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
if (this.dataPresenter.Equals(sender))
{
DataRecordPresenter drp = Utilities.GetAncestorFromType(e.OriginalSource as DependencyObject, typeof(DataRecordPresenter), true) as DataRecordPresenter;
if (drp != null)
{
// If we already have a selection then we don't want the Grids SelectionController to be called which will cause a capture of the mouse and prevent dragging.
if (drp.IsSelected)
{
e.Handled = true;
}
}
}
}
}
}

How to extract Information from Nodes in TreeView in Windows forms?

I have created a Winform. I want to show Subanatomy ID information using object of type Subanatomy after the node is selected how Should I do it.?
i have used all the neccessary libraries in my original code
` using System.Windows.Forms;
using basicObjectLib;
namespace WindowsFormsApplication12
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
LoadTreeItems();
}
public void LoadTreeItems()
{
// Dummy Data
// created a DLL Basic Class Object Conatining class definitions of anatomy subanatomy
#region Object
Anatomy an1 = new Anatomy();
an1.AnatomyID = 1;
an1.AnatomyName = "Anatomy1";
Subanatomy san1 = new Subanatomy();
san1.SubAnatomyID = 11;
san1.SubAnatomyName = "subAn1";
an1.SubanatomyList.Add(san1);
Subanatomy san2 = new Subanatomy();
san2.SubAnatomyName = "subAn2";
san2.SubAnatomyID = 2;
an1.SubanatomyList.Add(san2);
Anatomy an2 = new Anatomy();
an2.AnatomyID = 2;
an2.AnatomyName = "Anatomy2";
Subanatomy san21 = new Subanatomy();
san21.SubAnatomyName = "subAn1";
san21.SubAnatomyID = 21;
an2.SubanatomyList.Add(san21);
Subanatomy san22 = new Subanatomy();
san22.SubAnatomyName = "subAn2";
san22.SubAnatomyID = 22;
an2.SubanatomyList.Add(san22);
Anatomy an3 = new Anatomy();
an3.AnatomyID = 3;
an3.AnatomyName = "Anatomy3";
Subanatomy san31 = new Subanatomy();
san31.SubAnatomyName = "subAn1";
san31.SubAnatomyID = 31;
an3.SubanatomyList.Add(san31);
Subanatomy san32 = new Subanatomy();
san32.SubAnatomyName = "subAn2";
san32.SubAnatomyID = 32;
an3.SubanatomyList.Add(san32);
List<Anatomy> anatomyObj = new List<Anatomy>();
anatomyObj.Add(an1);
anatomyObj.Add(an2);
anatomyObj.Add(an3);
#endregion
foreach(Anatomy obj in anatomyObj)
{
TreeNode parentNode = new TreeNode();
parentNode = new TreeNode(obj.AnatomyName);
treeView1.Nodes.Add(parentNode);
foreach(Subanatomy subObj in obj.SubanatomyList)
{
TreeNode childNode = new TreeNode();
childNode = new TreeNode(subObj.SubAnatomyName);
parentNode.Nodes.Add(childNode);
}
}
}
private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
{
if (e.Action == TreeViewAction.ByMouse)
{
// name of treeNode
textBox4.Text = treeView1.SelectedNode.Name.ToString();
// to show the ID
textBox2.Text = "";
}
}
private void button1_Click(object sender, EventArgs e)
{
treeView1.ExpandAll();
}
}
public class WindowsFormApplication
{
public static void main()
{
Form1 _treeviewDemo = new Form1();
}
}
}`
you can use TreeNode.Tag to store your object.
when you create a TreeNode, assign the object you want to associate it with to the TreeNode Example:
treeNode.Tag=<object>
you can use it later by casting it
Example:
(<Class>)treeNode.Tag
In your code:
foreach(Subanatomy subObj in obj.SubanatomyList)
{
TreeNode childNode = new TreeNode();
childNode = new TreeNode(subObj.SubAnatomyName) { Tag = subjObj.SubAnatomyID };
parentNode.Nodes.Add(childNode);
}
and get data
private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
{
if (e.Action == TreeViewAction.ByMouse)
{
// name of treeNode
textBox4.Text = treeView1.SelectedNode.Name.ToString();
// to show the ID
textBox2.Text = ((int)treeView1.SelectedNode.Tag).ToString();
}
}
But I think better is
foreach(Subanatomy subObj in obj.SubanatomyList)
{
TreeNode childNode = new TreeNode();
childNode = new TreeNode(subObj.SubAnatomyName) { Tag = subjObj };
parentNode.Nodes.Add(childNode);
}
and
private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
{
if (e.Action == TreeViewAction.ByMouse)
{
Subanatomy suba = treeView1.SelectedNode.Tag as Subanatomy;
if (suba != null)
{
// name of treeNode
textBox4.Text = subA.SubAnatomyName;
// to show the ID
textBox2.Text = subA.SubAnatomyID.ToString();
}
}
}

Not able to fire SelectedNodeChanged event for populated TreeView node

I need to dynamically generate several treeview on my code and I want to be able to load nodes on demand. I have below code structures. My problem is SelectedNodeChanged event for populated TreeView node will not fire. Once you run below code sample, if you expand child node to several level and then click the child node, the label will not show text and the populated nodes collapse. Any idea is appreciated!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class TreeViewTest : System.Web.UI.Page
{
private const int Count = 2;
private string[] codeList = { "th", "os" };
protected void Page_Load(object sender, EventArgs e)
{
updateTree();
}
protected void updateTree()
{
treePanel.Controls.Clear();
TreeView[] treeList = new TreeView[Count];
for (int i = 0; i < Count; i++)
{
var tree = new TreeView();
tree.ID = "treelist" + i.ToString();
tree.TreeNodePopulate += TreeBranch_SelectedNodePopulate;
tree.SelectedNodeChanged += TreeBranch_SelectedNodeChanged;
string codeName = codeList[i];
TreeNode codeNode = new TreeNode(codeName, codeName);
codeNode.SelectAction = TreeNodeSelectAction.Select;
codeNode.PopulateOnDemand = true;
tree.Nodes.Add(codeNode);
tree.ExpandDepth = 2;
treePanel.Controls.Add(tree);
treeList[i] = tree;
}
}
protected void TreeBranch_SelectedNodeChanged(object sender, EventArgs e)
{
TreeView treeview = (TreeView)sender;
string text = treeview.SelectedNode.Text;
Label1.Text = text;
}
protected void TreeBranch_SelectedNodePopulate(object sender, TreeNodeEventArgs e)
{
LoadChildNode(e.Node);
}
public void LoadChildNode(TreeNode parentNode)
{
TreeNode childNode = new TreeNode("childNode","childNode");
parentNode.ChildNodes.Add(childNode);
childNode.PopulateOnDemand = true;
}
}
Try the following code.
treePanel.Controls.Clear();
TreeView[] treeList = new TreeView[codebaseCount]; //But I recommend you use List<TreeView> instead of TreeView[];
for (int i = 0; i < codebaseCount; i++)
{
var tree = new TreeView();
tree.ID = "treelist" + i.ToString();
tree.TreeNodePopulate += TreeBranch_SelectedNodePopulate;
tree.SelectedNodeChanged += TreeBranch_SelectedNodeChanged;
TreeNode newNode = new TreeNode(newName,newName);
newNode.SelectAction = TreeNodeSelectAction.None;
newNode.Expand();
tree.Nodes.Add(newNode);
tree.ExpandDepth = 2;
treePanel.Controls.Add(tree);
treeList[i] = tree;
// more code ...
}

Creating a Listview filter in WPF with a text box search

I am creating an application with an XML file called star.xml to store my data in a list view. I am very new to c# and programming and need any help
Basically, I want to be able to type in my search text box (called 'search') and for my list view (lstStar) to only show the matching records. I.e. typing in 'Audi' will only return those items.
any help will be much appreciated
jen
namespace StarinCar
{
public partial class MainWindow : Window
{
int hot = -2;
int Mildly_Moist = -2;
int Wet = -4;
int Very_Wet = -6;
private ObservableCollection<star> starData;
public MainWindow()
{
InitializeComponent();
starData = new ObservableCollection<star>();
lstStar.ItemsSource = starData;
try
{
XmlSerializer xs = new XmlSerializer(typeof(ObservableCollection<star>));
using (StreamReader rd = new StreamReader("star.xml"))
{
starData = xs.Deserialize(rd) as ObservableCollection<star>;
}
}
catch
{
}
lstStar.ItemsSource = starData;
lblAverage.Content = starData.Average(i => i.time).ToString();
lblFastest.Content = starData.Min(i => i.time).ToString();
lblSlowest.Content = starData.Max(i => i.time).ToString();
}
private void btnAdd_Click(object sender, RoutedEventArgs e)
{
star newStar = new star();
newStar.firstName = txtName.Text;
newStar.time = int.Parse(txtTime.Text);
newStar.car = txtCar.Text;
newStar.track = txtTrack.Text;
starData.Add(newStar);
if (txtTrack.Text.Contains("Hot") || (txtTrack.Text.Contains("hot") == true))
{
newStar.time = int.Parse(txtTime.Text) + hot;
}
if (txtTrack.Text.Contains("Mildly Moist") || (txtTrack.Text.Contains("mildly moist")) == true)
{
newStar.time = int.Parse(txtTime.Text) + Mildly_Moist;
}
if (txtTrack.Text.Contains("Wet") || (txtTrack.Text.Contains("wet") == true))
{
newStar.time = int.Parse(txtTime.Text) + Wet;
}
if (txtTrack.Text.Contains("Very Wet") || (txtTrack.Text.Contains("very wet")) == true)
{
newStar.time = int.Parse(txtTime.Text) + Very_Wet;
}
}
private void Window_Closed(object sender, EventArgs e)
{
XmlSerializer xs = new XmlSerializer(typeof(ObservableCollection<star>));
using (StreamWriter wr = new StreamWriter("star.xml"))
{
xs.Serialize(wr, starData);
}
}
}
}
You could use ICollectionView. So you would have your "overall"
star collection 'starData'. But your listbox itemssource would be bound to something like this:
public ICollectionView FilteredStars
{
get
{
ICollectionView source = CollectionViewSource.GetDefaultView(starData);
source.Filter = new Predicate<object>(FilterStars);
return source;
}
}
the logic that does the filtering here:
private bool FilterStars(object item)
{
bool b = false;
star a = item as star;
if (a != null)
{
if (a.Name.Contains(searchBoxText)) //your filter logic here
{
b = true;
}
else if String.IsNullOrWhiteSpace(searchBoxText)
{
b = true;
}
}
return b;
}
Basically, you have your main collection, then some logic that filters your main collection to a filtered collection, and that's what you should set itemssource of your listbox to. This, so far, is assuming you are going to put some kind of property change into your search text box and probably then click a button, like "Search" to then tell the list to check and re-populate to match the search term.
This is how I filter in a similar application
public IEnumerable<string> PastEntries1
{
get
{
if(string.IsNullOrEmpty(textValue))
{
return FieldDefString.PastEntries;
}
else
{
return FieldDefString.PastEntries.Where(x => x.StartsWith(textValue, StringComparison.OrdinalIgnoreCase));
}
}
}

dynamic control RegisterRequiresControlState

i use my web.config file to define a menu it work fine. But to improve system i want to store my created menu control in an object menu_ to reuse it on next call.
if i add menu_ control to my master page (like i did with generated version) i have a RegisterRequiresControlState error :
RegisterRequiresControlState could not be call before or after prerender.
public class tabloidMenu : ConfigurationElementCollection
{
private Menu menu_;
static public explicit operator Menu(tabloidMenu configMenu)
{
if (configMenu.menu_ != null) return configMenu.menu_;
Menu menu = new Menu();
menu.CssClass = "menu";
menu.EnableViewState = false;
menu.ViewStateMode = System.Web.UI.ViewStateMode.Disabled;
menu.IncludeStyleBlock = false;
menu.Orientation = Orientation.Horizontal;
if (tabloidConfigMenu.configMenu != null)
{
foreach (tabloidConfigMenuItem item in configMenu)
{
menu.Items.Add((MenuItem)item);
}
}
configMenu.menu_=menu;
return menu;
}
in my master page i use
protected void Page_Init(object sender, EventArgs e)
{
bool popupMode = Page.Request["mode"] == "popup";
if (!popupMode)
{
System.Web.UI.HtmlControls.HtmlLink cssLink = new System.Web.UI.HtmlControls.HtmlLink();
cssLink.Href = "~/Styles/Site.css";
cssLink.Attributes.Add("rel", "stylesheet");
cssLink.Attributes.Add("type", "text/css");
Page.Header.Controls.Add(cssLink);
//add menu
if (Tabloid.tabloidConfigMenu.configMenu != null)
{
Menu mn = (Menu)Tabloid.tabloidConfigMenu.configMenu.TopMenu;
mn.EnableViewState = false;
mn.ViewStateMode = System.Web.UI.ViewStateMode.Disabled;
Page.Master.FindControl("MenuHolder").Controls.Add(mn);
}
else
{
Label l = new Label();
l.Text = Tabloid.tabloidConfigMenu.lastError;
Page.Master.FindControl("MenuHolder").Controls.Add(l);
}
}
do you have an idea.
Thanks for your help.

Categories

Resources