I am trying to read value from a listbox item that is on another thread.
I tried to make a new method to run the invoke command, I can manage to send a command to the listbox like add via the invoke method but i cant seem to get a response, i cant seem to get the value of the item, i have tried a few ways, once i change it from a void to a string things start to get hairy...
thread t1 = new thread(thethread)
t1.start()
public void thethread()
{
string text = readListBoxSelected(listBox1) + " lala" ;
}
public static string readListBoxSelected(ListBox listbox)
{
if (listbox.InvokeRequired)
{
return (string)listbox.Invoke(
new Func<String>(() => readListBoxSelected(listbox))
);
}
else
{
string varText = listbox.SelectedValue.ToString();
return varText;
}
}
Above is a example of what i am trying to do.
Here is the error:
System.NullReferenceException was
unhandled by user code
Message=Object reference not set to an
instance of an object.
Source=** StackTrace:
at **.Form1.readListBoxSelected(ListBox listbox) in e:\documents and
settings\scott\my documents\visual
studio
2010\Projects*****\Form1.cs:line
133
at ***.Form1.<>c_DisplayClass5.b_3()
in e:\documents and settings\scott\my
documents\visual studio
2010\Projects******\Form1.cs:line
127 InnerException:
I imagine what is wrong is exactly what it says "Object reference not set to an instance of an object"....... All my variables seem to be declared as fair as i am aware, how can i correct this??
I get the feeling i am going about the entire thing wrongly.... 0_o
Thanks in Advance,
Scott
Try This
public static string readListBoxSelected(ListBox listbox)
{
if (listbox.InvokeRequired)
{
return (string)listbox.Invoke(
new Func<String>(() => readListBoxSelected(listbox))
);
}
else
{
if(istbox.SelectedValue != null)
return listbox.SelectedValue.ToString();
else
return String.Empty
}
}
Code looks fine, the problem seems on the SelectedValue, is it null. ???
Thanks guys,
You where correct, Problem was it was returning a null value..
I was so sure that i was selecting the item correctly i never thought it could be the problem.
Turns out the problem was two things:
1)
The way i was selecting item, i was using listbox.Selecteditem = 1 , now if i use listbox.setSelected(1,true) all is good :)
and
2)
The way i was getting the items text was wrong, listbox.SelectedValue is nothing, it dosnt do what we all imagine it to do... the call i need was listbox.Text .........
public static string readListBoxSelected(ListBox listbox)
{
if (listbox.InvokeRequired)
{
return (string)listbox.Invoke(
new Func<String>(() => readListBoxSelected(listbox))
);
}
else if(listbox.Text != null)
{
return listbox.Text.ToString();
}
else
return String.Empty;
}
public void selectListBoxItem(ListBox listbox, int num)
{
Invoke(new MethodInvoker(delegate { listbox.SetSelected(num,true); }));
}
I must say this is the most anoying thing i have ever done... Everything requires i write a delegate / invoke method for it... Everything... woudlnt something so common be supported by .net on the fly....
Seems a waist of time to write individual delegates for EVERYTHING...
Thanks guys all is working now, yesterday i couldn't foresee me getting to this point,
Overall problem was Wrong Calls, the invoke was all fine :)
Scott
EDIT:
ok it was returning NULL simply because listbox.SelectedValue isnt really the call im after to read the selectedvalue (you would think it was), if i change it to listbox1.text all works fine.... rather silly this .net object oriented stuff if i do say so....
I must say what a joke... thats kindly destroyed my faith in object oriented programming..
I understand this is not a discussion fourm but honestly the call SelectedValue.toString() should do what we all think it will do.... nope we need to use .Text to get what we require 0_o.........
Related
I'm relatively new to XAML / Xamarin and I'm running into something I'm hoping someone can help me clarify.
I know the title is misleading, but I couldn't put it any different.
I have the following property in my ViewModel:
private ObservableCollection<Schedule> _scheduleList;
public ObservableCollection<Schedule> ScheduleList
{
get
{
return _scheduleList;
}
set
{
value = _scheduleList;
}
}
Somewhere down the line, I do something like this:
private void DayFilter(string week)
{
try
{
var list = _scheduleList.Where(x => x.ScheduleDate.DayOfWeek.ToString() == week);
ObservableCollection<Schedule> newlist = new ObservableCollection<Schedule>(list);
ScheduleList.Clear(); // <- this line clears out _scheduleList as well
foreach (var item in newlist)
{
ScheduleList.Add(item);
}
}
catch (Exception ex)
{
throw ex;
}
}
Whenever ScheduleList.Clear() is called, it also clears out _scheduleList which is the private field.
I know this has something to do with the fact that this is ObservableCollection, but the requirement is that it should be, and I could not find a way to retain the value on _scheduleList, as I need this field populated throughout the lifetime of the application.
Is there away that the field _scheduleList does not get cleared out?
This is just how C# works
ScheduleList.Clear();
returns a reference to _scheduleList (that's what the public get does) and then calls Clear on it.
In your scenario, you probably need to maintain two completely separate copies of your data - the original, as well as one that you use for filtering/displaying the data.
I have a MVVM property to update and there are some situations where I want to cancel the change inside the setter.
I have read several SO posts explaining that we need to use a dispatcher to do this:
link2
link1
However, it does not work in my case.
For any reason, the XAML control still updates.
I am confused as I can see the debugger run the dispatcher method after the properrty is set to the new value. It does run the code that should switch it back, but the control sticks to the new value instead of switching back to the old one.
My code is as follows:
private DB_VisionParameters _MyProp;
public DB_VisionParameters MyProp
{
get
{
return _MyProp;
}
set
{
if (_MyProp == value)
{
return;
}
if ( isInvalidTest)
{
MyType storedValue = _MyProp;
//switch back to update interface with old value
DB_VisionParameters previousVisionParameter = _MyProp;
if (DispatcherHelper.UIDispatcher != null)
DispatcherHelper.UIDispatcher.BeginInvoke(
(new Action(() =>
{
_MyProp = storedValue;
RaisePropertyChanged("MyProp");
})), DispatcherPriority.ContextIdle);
return;
}
_MyProp = value;
RaisePropertyChanged("MyProp");
}
}
Looks like SO solutions to me but I have probably missed something :(
I tried your code and if MyProp has the right value (i.e. the old value) and if it is not modified by anyone else then it should update.
As you have also confirmed the same that you had it being modified in your version of code thus the instance was never the same and it reflected with newer version details on UI, which was not as expected.
I have an object which is made of many other objects! I am trying to find the value of of one of the properties (an enum) but can't.
Now, normally if I want to check if an object is null I can do
if (object == null)
but this results in the same error.
I tried
if (object.Equals(null)) and the same error.
The error message I'm getting is objectName threw exception: System.NullReferenceException: Object reference not set to an instance of an object..
I'm trying to determine if my object is instantiated or not. Now, I can stick this into a try catch, if it errors then I know it's not, but to me this feels very wrong (although I may not have a choice).
The other problem I have is this project isn't mine and is a black box to everyone and so I can't make any changes to the original object! This means, all I have is what I have got, an object which may or may not be instantiated and I need a way of telling.
Other than the try catch, do I have any other options?
EDIT
So, the object is
public partial class SaveBundleResponse
{
SaveBundleResponseHeader header;
}
public partial class SaveBundleResponseHeader
{
private SaveBundleResponseHeaderStatus status;
}
public enum SaveBundleResponseHeaderStatus
{
Success, Fail, OK, OtherStates
}
So the SaveBundleResponse is created initially, the instance is then passed through a 'workflow' style environment and each property becomes 'populated/updated' etc as it goes deeper into the workflow. However, in a few situations, the enum is never set.
The problem is, I need to know the value of the enum (or if it is null).
The code I am trying to use is
if (saveBundleResponse.Header.Status // what ever happens, it fails at this point as Status is not initiated.
if (saveBundleResponse != null)
{
var header = saveBundleResponse.Header;
if (header != null)
{
var status = header.Status;
}
}
You should be able to use something like this:
SaveBundleResponse sbr = ...;
if (sbr.Header != null && !sbr.IsDisposed)
{
//Do the work
}
This should work (if the class is not a control you can't use the IsDisposed check).
I am wondering why this code works fine and comiler doesnt generate any errors or warnings?
class Program
{
static int _value;
static int MyValue
{
get { return _value; }
set { _value = 5; }
}
static void Main()
{
Console.WriteLine(Program.MyValue); //This line print 0 (defoult value of int variables)and its normal
Program.MyValue = 10; //after calling the Set accssor we will see that
Console.WriteLine(Program.MyValue); //The result is 5
Console.ReadLine();
}
is this any usefull or special thing? or could it be a technic in Property initialization? thanks in advance.
EDIT:
It seems what we have here is a Readonly Property with defoult value am I right?
The set-accessor is nothing other than a method with a parameter, the "value"-parameter. It's up to the method what it does and what it does not.
void Set__MyValue(int value){
_value=5;
}
The code is valid C#, so wouldn't cause errors or warnings.
Code in getters and setters can be anything, so can't really be statically checked - even if you do something strange like ignore the value passed into the setter, that might be exactly the right thing for your code.
Since the set statement is actually just a convenient way of specifying a full method (i.e. set_MyValue(int value)) all the normal rules of functions apply. In particular, there is no obligation to use the parameters if you don't want to.
While your example is contrived, there are plenty of situations where it makes sense to ignore the value passed in. For example, suppose you wanted to make sure a particular string property was never null. You might do something like this:
private string _myProp = string.Empty;
public string MyProp
{
get
{
return _myProp;
}
set
{
if (value == null)
{
_myProp = string.Empty;
return;
}
_myProp = value;
}
}
We ignore value if we want to, and don't otherwise.
This code is pretty valid and also can be usefull in certain scenarious . If you immagine that you want raise an event/WPF command on _value changing, log that stuff, do any other meaningful for you stuff there. Having this kind of management setting the _value directly will cause "silent" assignment, setting this _value via property can cause notifications.
I will never do something like this honestly, cause it's confusional and not clear for someone who doesn't really understand your code, but by the way it's kind of "solution" too.
Regards.
The property will be converted as 2 different methods in IL(one for set the value and the other is to return the value) and ignoring a parameter is valid in a method!
You can check this by using the tool ildasm.exe(which comes with Visual Studio).
Trying to work out this whole web part personalisation, and trying to implement it for a list box.
Well the end result will be two list boxes, with interchangeable values (ie, a value will only exist in one of the listboxes)
But I can't maintain the datasource for it. So maybe I'm going about it wrong?
This is what I have for a test H2 tag on the page
[Personalizable(PersonalizationScope.User)]
public string LabelText {
get { return h2Test.InnerText; }
set { h2Test.InnerText = value; }
}
And it works fine, if I have a textbox and use it to change the value of LabelText, then when I close the browser it automagically persists the change.
So I thought, ok, then maybe the same will work with a list box
[Personalizable(PersonalizationScope.User)]
public DomainList Domains {
get { return (DomainList)lstBxDomains.DataSource; }
set {
lstBxDomains.DataSource = value;
lstBxDomains.DataBind();
}
}
Where DomainList is just a class which extends List, and Domain is just a three field class, int, string, string.
But it doesn't, so is this too complicated for the webpart personalisation automagican, or have i just implement it wrongly (Which is more than likely)
This is my event handler to remove the items from the list:
protected void btnRemDomain_Click(object sender, EventArgs e) {
if (IsPostBack && lstBxDomains.SelectedIndex > -1) {
for (int i = 0; i < lstBxDomains.Items.Count; i++) {
if (lstBxDomains.Items[i].Selected) {
Domains.Remove(Domains.Find(d => d.ID.ToString() == lstBxDomains.Items[i].Value));
}
}
Domains = Domains;
}
}
The Domains=Domains; line is in there to see if explicitly setting the value made a difference (as Removing doesn't acutally reset the value of the field), but it doesn't. I've also tried creating a new local DomainList setting it to the global one, and then doing the remove/find on it, and then setting the local one to the global. But not working either.
I have managed to resolve this by using WebPart.SetPersonalizationDirty(this); in the set accessor of Domains, but would someone mind confirming if this is an appropriate way to do it?