unable to cast from object to Treeviewitem - wpf

I'm trying to Cast from an object to a TreeviewItem and getting the next error:
"unable to cast object of type 'system.string' to type 'system.windows.controls.treeviewitem'."
For 2 days I'm searching for a solution to this, I saw many examples of explicit cast to treeviewitem so I think it legit but its not working.
foreach (Req ObjReq in reqFilter.NewList())
{
index = PM_TreeView.Items.Add(ObjReq.Name);
TreeViewItem ParentNode = new TreeViewItem();
//this is the Cast I try to do
ParentNode = (TreeViewItem)PM_TreeView.Items[index];
ParentNode.Tag = ObjReq.ID;
reqFilter["RQ_FATHER_ID"] = (ObjReq.ID.ToString());
reqFilter.KeepHierarchical = true;
if (reqFilter.NewList().Count > 0)
FillReqTreeView(reqFilter, ObjReq);
}
The main idea is to populate the List in the reqFilter to a Treeview.

The message says you are trying to cast a STRING to a TreeViewItem.
The third line in your code
index = PM_TreeView.Items.Add(ObjReq.Name);
adds a STRING to the Items collection yet the seventh tries to cast this same string to a TreeViewItem
ParentNode = (TreeViewItem)PM_TreeView.Items[index];
Instead of adding a string, add a new TreeViewItem with the Header value you want

Related

Finding the wrong UIElement in Grid

Problem: When I select a check box (in Column '1'), the OnSelection event should find a Label on Column '0' in the same Row, but I am getting:
System.InvalidCastException: 'Unable to cast object of type 'System.Windows.Controls.CheckBox' to type 'System.Windows.Controls.Label'.'
I am initializing the view as such:
Label lbName = new() { Content = "labelName" };
Grid.SetColumn(lbName, 0);
GrWindow.Children.Add(lbName);
CheckBox ckSelection = new();
ckSelection.Checked += OnSelection;
Grid.SetColumn(ckSelection, 1);
GrWindow.Children.Add(ckSelection);
And on the OnSelection method, where the exception is triggered:
string? labelName = GrWindow.Children.
Cast<Label>().
First(e => Grid.GetRow(e) == row && Grid.GetColumn(e) == 0).
Content as string;
In other place in my app, I am using a very similar approach to get a name from Row '0' and works fine.
There is only one children on every row/column = '0', and its a label, I dont know how to debug such situations, since the checkbox is on column='1'.
Thanks in advance.
Replace
.Cast<Label>()
with
.OfType<Label>()
to get only the Labels.
Otherwise you are trying to cast all child elements to Label, which will of course fail for the CheckBox.
An alternative to querying the Children collection might be to assign the associated Label to the Tag property of the CheckBox
ckSelection.Tag = lblName;
and get it back in the event handler by
var checkBox = (CheckBox)sender;
val label = (Label)checkBox.Tag;

LINQ to SQL query to populate ListBox returns wrong results

Hello here's a LINQ to SQL query :
private void Stk_DT_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
DataTable dt = new DataTable();
DataGrid grid = sender as DataGrid;
#region Buttons Picking Libres
using(BdCretsDataContext dc=new BdCretsDataContext())
{
var placement = (from p in dc.PICKING
where p.ART_CODE == ArtCode_TxtBox.Text
select new { p.R_PLACEMENT }).Distinct().ToList();
LB.ItemsSource = placement;
}
#endregion
}
With this query I want to fill a ListBox. But I get this result :
All I want is just: 53.
Thanks for helping me
The point is that select new { p.R_PLACEMENT } creates a collection of objects that have a property called R_PLACEMENT. The ToString() of this object, which is invoked by the ListBox, returns a string representation of this object: { R_PLACEMENT = 53 }. You have to unwrap or collect the values from this property:
LB.ItemsSource = placement.Select(row => row.R_PLACEMENT);
This returns a collection of values only.
This is because you create a new (anonymous) type within select new { p.R_PLACEMENT }.
Your placement variable will thus hold a List<> of this new type. The ListBox however does not know how to display items of this type.
To make the ListBox display something useful you must tell it what it should make out of this anonymous type. ListBox does not figure out it on its own.
The simplest solution would probably be to create placement like this:
var placement = (from p in dc.PICKING
where p.ART_CODE == ArtCode_TxtBox.Text
select p.R_PLACEMENT.ToString()).Distinct().ToList();
(From your example I deduce that R_PLACEMENT is of some numeric type.) The .ToString() suffix makes placement a List<string> which the ListBox will be glad to display correctly.

WPF - cannot parse TextBlock element from string

I'm new in WPF
I need to get string param, create an UIElement and attach it to the view.
Parsing the element from the string is failed, I don't know why.
Here is the code:
public void addElementToView(string str)
{
object obj = XamlReader.Load(new XmlTextReader(new StringReader(str)));
UIElement elem = (UIElement)obj;
SpecialContent.Children.Add(elem);
}
call addElementToView("<TextBox Text=\"hello\"/>") fails with the following exception:
A first chance exception of type 'System.Windows.Markup.XamlParseException' occurred in PresentationFramework.dll
Additional information: 'Cannot create unknown type 'TextBlock'.' Line number '1' and line position '2'.
It failes in this row:
object obj = XamlReader.Load(new XmlTextReader(new StringReader(str)));
Any idea?
You should have the necessery namespace in xml. like following,
addElementToView("<TextBox Text=\"hello\" xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"/>");

Unable to cast object of type '<>f__AnonymousType0`2[System.String,System.Int32]' to type 'System.IConvertible'

I am trying to populate a data list box to text box on list box's click event but I found this error
Additional information: Unable to cast object of type '<>f__AnonymousType0`2[System.String,System.Int32]' to type 'System.IConvertible'
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
StudenRecordDataContext std = new StudentRecordDataContext();
int selectedValue = Convert.ToInt32(listBox1.SelectedValue);
StudentRecord sr = std.StudentRecords.Single(s =>s.ID==selectedValue);
txtId.Text = sr.ID.ToString();
txtName.Text = sr.Name;
txtPassword.Text = sr.Password;
txtCnic.Text = sr.CNIC;
txtEmail.Text = sr.Email;
}
I think the error is on line StudentRecord sr = std.StudentRecords.Single(s =>s.ID==selectedValue);
Where does that error come from and what do I need to change to fix that error?
I'm sorry to say so but you provided us with the wrong diagnosis of the line your program fails.
The culprit is this line:
int selectedValue = Convert.ToInt32(listBox1.SelectedValue);
I expect you have earlier populated that listbox1 with a collection from StudentRecords coming from an instance of your StudentRecordDataContext.
If you select a value from the listbox the SelectedValue holds the object you added to the items collection (or indirectly by setting the DataSource property).
To fix your code you could first make sure the object becomes a StudentRecord again. That is not that easy because you created an anonymous type, I expect something like:
listbox1.DataSource = new StudentRecordDataContext()
.StudentRecords
.Select(sr => new { Name = sr.Name, ID = sr.ID });
When you try to retrieve the SelectedValue you get that anonymous type, not something that is strongly typed.
Instead of adding an anonymous type, create a new class that has the properties for the Name and the Id:
class StudentRecordItem
{
public string Name {get; set;}
public int ID {get; set;}
}
When you populate the Datasource create StudentRecordItem classes for each record and add those to the datasource.
listbox1.DataSource = new StudentRecordDataContext()
.StudentRecords
.Select(sr => new StudentRecordItem { Name = sr.Name, ID = sr.ID });
The your code can become something like this:
StudentRecordItem selectedStudent = listBox1.SelectedValue as StudentRecordItem;
if (selectedStudent == null)
{
MessageBox.Show("No student record");
return;
}
int selectedValue = selectedStudent.ID;
You don't need the Convert.ToInt32 because I assume ID is already an int.
Remember that the debugger in Visual Studio shows the actual types and values of all your properties and variables. When a type conversion fails you can inspect there what the actual type is you're working with.

Object reference not set to an instance of an object during xml serialization and problem with selection of combobox item upon loading

question 1. I have this issue of "Object reference not set to an instance of an object" when my Majorlabel is empty and this occurs after i try to do a save button click on xml serialization. How can i fix this?
private void SaveButton_Click(object sender, RoutedEventArgs e)
{
string savepath;
SaveFileDialog DialogSave = new SaveFileDialog();
// Default file extension
DialogSave.DefaultExt = "txt";
// Available file extensions
DialogSave.Filter = "XML file (*.xml)|*.xml|All files (*.*)|*.*";
// Adds a extension if the user does not
DialogSave.AddExtension = true;
// Restores the selected directory, next time
DialogSave.RestoreDirectory = true;
// Dialog title
DialogSave.Title = "Where do you want to save the file?";
// Startup directory
DialogSave.InitialDirectory = #"C:/";
DialogSave.ShowDialog();
savepath = DialogSave.FileName;
DialogSave.Dispose();
DialogSave = null;
FormSaving abc = new FormSaving();
if (!string.IsNullOrEmpty(MajorversionresultLabel.Content.ToString()))
{
abc.Majorversion = MajorversionresultLabel.Content.ToString();
}
abc.Startzbuildfrom = StartzbuildcomboBox.SelectedItem.ToString();
using (Stream savestream = new FileStream(savepath, FileMode.Create))
{
XmlSerializer serializer = new XmlSerializer(typeof(FormSaving));
serializer.Serialize(savestream, abc);
}
}
As recommended,
here is the line of error:
if (!string.IsNullOrEmpty(MajorversionresultLabel.Content.ToString()))
{
abc.Majorversion = MajorversionresultLabel.Content.ToString();
}
Question 2. I used this line to save my combo box selection:
abc.Startzbuildfrom = StartzbuildcomboBox.SelectedItem.ToString();
and in my load i have this line:
StartzbuildcomboBox.SelectedItem = abc.Startzbuildfrom
why wont it select the combobox selection previously?
As a first note, I'd recommend only putting one question into a single query here. Makes it easier.
For your second question, my guess is that you're running into a reference variable problem. I think that calling the ToString() method on the SelectedItem actually creates an entirely new string variable. Then, when you try to set the selected item later, it can't find the new string as a possible item to select because, even though the two strings have the same value, they are different objects. I would maybe recommend that you either:
1) Set the selected item by searching through your combo box contents to find a string whose value matches the one you've saved
or
2) Save the actual reference by saying abc.Startzbuildfrom = StartzbuildcomboBox.SelectedItem. Then set the selected item from that reference.
I suspect that MajorversionresultLabel is null, or MajorversionresultLabel.Content is null. Thus your statement
if (!string.IsNullOrEmpty(MajorversionresultLabel.Content.ToString()))
will throw a NullReferenceException. Try this instead:
if (MajorversionresultLabel != null && MajorversionresultLabel.Content != null && MajorversionLabel.Content.ToString() != string.Empty)
I bet your NullReferenceException will go away.

Resources