I have one static method which I call from another class when I need update data in listbox. But then I need scroll listbox to last item. Here is code:
public static void updateMessages()
{
MyDatasCurentUser.Clear();//clear messages from previewous user from datas
foreach (var items in UniDB.returnlistOfMessagesData(IdOfChoosenUser, MainContentPage.myID))
{
_mydataCurentUser.Add(new BindingData
{
MessengerReadTime = new DateTime(items.readTime.Year, items.readTime.Month, items.readTime.Day, items.readTime.Hour, items.readTime.Minute, 0),
MessengeFullName = items.senderName,
MessengerTime = new DateTime(items.sendTime.Year, items.sendTime.Month, items.sendTime.Day, items.sendTime.Hour, items.sendTime.Minute, 0).ToString("dd.MM.yyyy - HH:mm"),
MessengerMessage = items.message,
MessengerIsFromMe = items.isFromMe,
});
}
lbChoosenMessagesUsers.ScrollIntoView(lbChoosenMessagesUsers.Items.Last());
}
But I get error cannot access to non static field in static context at this: lbChoosenMessagesUsers.ScrollIntoView(lbChoosenMessagesUsers.Items.Last());
Is there any way how I can do this lbChoosenMessagesUsers.ScrollIntoView(lbChoosenMessagesUsers.Items.Last()); when is method updateMessages() called?
If you have a non static method of one class:
class Form1
{
public void UpdateMessages()
{
// ...
lbChoosenMessagesUsers.ScrollIntoView(lbChoosenMessagesUsers.Items.Last());
}
}
And you want to call it from an object of a different class, that object will need a reference to the first object. A common solution is to pass the reference to the first object into the constructor of the second:
class OtherClass
{
Form1 _form;
OtherClass(Form1 form)
{
_form = form;
}
void Method()
{
//can access the methods of the other object
_form.UpdateMessages();
}
}
Alternatively you could pass the object in later:
class OtherClass
{
public void Method(Form1 form)
{
form.UpdateMessages();
}
}
Related
I have a WPF application. In one of the XAML I have used Name attribute like as follows
x:Name="switchcontrol"
I have to access the control/property in .cs file using this.switchcontrol
My question is, I need to access the control in static method like
public static getControl()
{
var control = this.switchcontrol;//some thing like that
}
How to achieve this?
this is not accessible in static method. You can try save reference to your instance in static property, for example:
public class MyWindow : Window
{
public static MyWindow Instance { get; private set;}
public MyWindow()
{
InitializeComponent();
// save value
Instance = this;
}
public static getControl()
{
// use value
if (Instance != null)
var control = Instance.switchcontrol;
}
protected override void OnClosed(EventArgs e)
{
base.OnClosed(e);
Instance = null; // remove reference, so GC could collect it, but you need to be sure there is only one instance!!
}
}
Some alternatives to Tony's method - you could pass in the window (or whatever xaml construct you are using) as a reference to the method, e.g.
public static void GetControl(MainWindow window)
{
var Control = window.switchcontrol;
}
if you are going to be passing several different derived types of Window, you could also do this:
public static void GetControl(Window window)
{
dynamic SomeTypeOfWindow = window;
try
{
var Control = SomeTypeOfWindow.switchcontrol;
}
catch (RuntimeBinderException)
{
// Control Not Found
}
}
I have a Program class which has:
private static ClientBase objClientBase = new ClientBase(new List<RecordType> { RecordType.none }, ModuleType.Monitor);
static void Main(string[] args)
{
objClientBase.Connect(); //IRRELEVANT
objQueueMon = new Main(); //<-INSIDE THIS IS WHERE I WANT TO ACCESS objClientBase
objClientBase.MainModuleThreadManualResetEvent.WaitOne(); //IRRELEVANT
}
This Progam creates a Main class instance as you see:
objQueueMon = new Main();
Notice that they are separated in different files, but the Main class instance is created inside the Program class.
Inside my Program class I want to access that objClientBase.
Do I have to create a constructor method and pass it or make a public access to it?
So what I want to achieve is, inside the Main class, do a objClientBase.FUNCTION
You can do exactly what you just said:
public class Main {
private ClientBase _caller;
public Main (ClientBase caller) {
_caller = caller;
}
}
Or, you can set it later
public class Main {
private ClientBase _caller;
public Main () {
}
// only your assembly sets it
internal SetClientBase(ClientBase cb) {
_caller = cb;
}
// but anyone gets it
// Now you can let some client execute "Function"
public ClientBase Caller {
{return _caller;}
}
}
Just an example
Change the constructor of your Main class to accept a ClientBase object, like this:
public class Main
{
private ClientBase _clientBase;
public Main(ClientBase clientBase)
{
_clientBase = clientBase;
}
public void SomeMethod()
{
// Use ClientBase.FUNCTION here
_clientBase.FUNCTION();
}
}
I want to create a custom message box for a program so I added a windows form item. I would like it to behave like MessageBox in that it is static and I just call MessageBox.Show(a, b, c, ...). In the forms designer, however, I don't see how I can make it static. Can I just add static to the code? Is there a property setting I'm missing in the designer mode?
Thanks!
MessageBox is not a static class, the Show method however is. Make Show static, in code. E.g.
public class MyMessageBox : Form
{
public static int MyShow()
{
// create instance of your custom message box form
// show it
// return result
}
}
It is a regular class with one method as static which instantiate new instance and act.
public class MyMessageBox
{
public static MyResult Show(params)
{
var myMessageBox = new MyMessageBox();
myMessageBox.Message = params ...
return myMessageBox.ShowDialog();
}
}
Add a static method to your form that displays itself and returns a DialogResult:
public partial class MyMessageBoxForm : Form {
public static DialogResult Show(string message) {
using (MyMessageBoxForm form = new MyMessageBoxForm(message)) {
return form.ShowDialog();
}
private MyMessageBoxForm(string message) {
// do something with message
}
}
If you want create static Form1 for access to it without object reference, you can change Program.cs:
public class Program
{
public static Form1 YourForm;
[STAThread]
static void Main(string[] args)
{
using (Form1 mainForm = new Form1())
{
YourForm = mainForm;
Application.Run(mainForm);
}
YourForm = null;
}
}
and call Form1 class methods from any place of your program:
Program.YouForm.DoAnything();
Do not forget to call Invoke for access from other threads.
I've searched Google all day and can't find the correct answer to my issue, hoping someone here can help me.
So, in the "Main" form I have the method to show a form that needs to be centered directly above the parent form (frmMain). Normally I would call ShowDialog(this) to see the parent, but for some reason I have to set the loadNewsFeedItem to static in order to see the method from the flpNewsFeedHeader : Label derrived class (below). The OnClick event triggers the method loadNewsFeedItem().
When I call this to set the parent, I'm getting the message "Keyword 'this' is not valid in a static property, static method, or static field initializer"
namespace NewsFeeds
{
public partial class FrmMain : Form
{
public static void loadNewsFeedItem()
{
frmNewsFeedView frmFeedView = new frmNewsFeedView(FrmFuncs.selFeedID);
frmFeedView.ShowDialog(this); // Error occurs on this line, when calling this via a static method
}
}
}
public class flpNewsFeedHeader : Label
{
private int FeedID = 0;
public int theFeedID
{
get { return FeedID; }
set { FeedID = value; }
}
protected override void OnClick(EventArgs e)
{
FrmFuncs.selFeedID = FeedID;
Thread thrShowFeed = new Thread(new ThreadStart(FrmMain.loadNewsFeedItem));
thrShowFeed.Start();
}
}
Can someone please give me a corrected code example or a hint as to how to get the loadNewsFeedItem() to be visible without setting the accessor to static, or how to work around this in a static accessor?
Thanks in advance!
Chris
Edit: used ActiveForm for owner.
public partial class FrmMain : Form
{
public static void loadNewsFeedItem(Form owner)
{
frmNewsFeedView frmFeedView = new frmNewsFeedView(FrmFuncs.selFeedID);
frmFeedView.ShowDialog(owner);
}
}
}
public class flpNewsFeedHeader : Label
{
private int FeedID = 0;
public int theFeedID
{
get { return FeedID; }
set { FeedID = value; }
}
protected override void OnClick(EventArgs e)
{
FrmFuncs.selFeedID = FeedID;
// Shouldn't need a new thread. Already on the GUI thread.
FrmMain.loadNewsFeedItem (System.Windows.Forms.Form.ActiveForm);
}
}
may be you mean this:
frmFeedView.Owner = System.Windows.Forms.Form.ActiveForm;
frmFeedView.ShowDialog();
In a static method, this is meaningless. One option is to skip the parameter
frmFeedView.ShowDialog();
The other option is to setup a static variable as shown below (but beware, it can have side effects if you try to open multiple instances of FrmMain)
public partial class FrmMain : Form
{
private static FrmMain staticInstance;
public FrmMain()
{
staticInstance = this;
InitializeComponent();
...
}
public static void loadNewsFeedItem()
{
frmNewsFeedView frmFeedView = new frmNewsFeedView(FrmFuncs.selFeedID);
frmFeedView.ShowDialog(staticInstance );
}
I have created a small application but I would now like to incorporate some type of logging that can be viewed via listbox. The source of the data can be sent from any number of places. I have created a new logging class that will pass in a delegate. I think Im close to a solution but Im receiving a NullReferenceException and I don’t know the proper solution. Here is an example of what Im trying to do:
Class1 where the inbound streaming data is received.
class myClass
{
OtherClass otherClass = new OtherClass();
otherClass.SendSomeText(myString);
}
Logging Class
class OtherClass
{
public delegate void TextToBox(string s);
TextToBox textToBox;
Public OtherClass()
{
}
public OtherClass(TextToBox ttb)
{
textToBox = ttb;
}
public void SendSomeText(string foo)
{
textToBox(foo);
}
}
The Form
public partial class MainForm : Form
{
OtherClass otherClass;
public MainForm()
{
InitializeComponent();
otherClass = new OtherClass(this.TextToBox);
}
public void TextToBox(string pString)
{
listBox1.Items.Add(pString);
}
}
Whenever I receive data in myClass, its throwing an error. Any help you could give would be appreciated.
Remove the empty constructor and pass the proper delegate in.
class OtherClass
{
public delegate void TextToBox(string s);
private readonly TextToBox textToBox;
public OtherClass(TextToBox textToBox)
{
if (textToBox == null)
throw new ArgumentNullException("textToBox");
this.textToBox = textToBox;
}
public void SendSomeText(string foo)
{
textToBox(foo);
}
}
Change your OtherClass to check for null:
class OtherClass
{
public delegate void TextToBox(string s);
TextToBox textToBox;
Public OtherClass()
{
}
public OtherClass(TextToBox ttb)
{
textToBox = ttb;
}
public void SendSomeText(string foo)
{
var handler = this.TextToBox;
if(handler != null)
{
textToBox(foo);
}
}
}
Now the reason you're getting the exception though is because in your myClass when you're creating a new OtherClass, you're not providing a method the delegate should "point" to. Therefore, when you're OtherClass calls textToBox(foo); there's no method behind it, and it blows up.
In myClass, you're not calling the overloaded OtherClass constructor that takes a TextToBox, so textToBox(foo) fails because textToBox has not been set.
Can you show the code where myClass is initialized and called?
You should pass in myClass constructor you OtherClass instance created in MainForm, don't create OtherClass instance in myClass it's not the instance to which you attached handler.