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\"/>");
Related
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.
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.
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
Using Windows forms and linq to Sql, I bound a datagridview to Products Table, I added to the form 1 Textbox to input the searched text.
I wonder how to position the datagridview according to the text entered to find a given ProductName.
Here I do not want to filter rows, I only want to reposition datagrid after each character entered, the used code:
private void textBox1_TextChanged(object sender, EventArgs e)
{
var searchValue = textBox1.Text.Trim().ToUpper();
var qry = (from p in dc.Products
where p.ProductName.ToUpper().StartsWith(searchValue)
select p).ToList();
int itemFound = productBindingSource.Find("ProductName", searchValue);
productBindingSource.Position = itemFound;
}
The execution of code give the next error: System.NotSupportedException was unhandled at the ligne:
int itemFound = productBindingSource.Find("ProductName", searchValue);
Any idea please ?
The MSDN documentation for BindingSource has the answer:
The Find method can only be used when the underlying list is an
IBindingList with searching implemented. This method simply refers the
request to the underlying list's IBindingList.Find method. For
example, if the underlying data source is a DataSet, DataTable, or
DataView, this method converts propertyName to a PropertyDescriptor
and calls the IBindingList.Find method. The behavior of Find, such as
the value returned if no matching item is found, depends on the
implementation of the method in the underlying list.
When you call this method on a BindingSource whose underlying data source does not implement IBindingList then you see the exception (thrown by the default implementation of IBindingList.FindCore:
System.NotSupportedException: The specified method is not supported.
You don't show what you bind the binding source to but clearly it doesn't implement this method.
Annoyingly, BindingList<T> the recommended list type to use for your data source does not provide a FindCore implementation.
If you are using BindingList you will need to create your own custom type. Here is the code for an absolutely bare bones implementation of a BindingList that supports find:
public class FindableBindingList<T> : BindingList<T>
{
public FindableBindingList()
: base()
{
}
public FindableBindingList(List<T> list)
: base(list)
{
}
protected override int FindCore(PropertyDescriptor property, object key)
{
for (int i = 0; i < Count; i++)
{
T item = this[i];
if (property.GetValue(item).Equals(key))
{
return i;
}
}
return -1; // Not found
}
}
You can do lots with your own implementations of BindingList such as supporting sorting. I've left my answer as just the minimum to support the find method. Search for SortableBindingList if you want to know more.
To use this class do something like this:
var qry = (from p in dc.Products
where p.ProductName.ToUpper().StartsWith(searchValue)
select p).ToList();
FindableBindingList<YourType> list = new FindableBindingList<YourType>(qry);
dataGridView1.DataSource = list;
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.