C# Set Form Parent after calling method from another class - c#

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 );
}

Related

Attribute to mark as "internal use"

I made a class which requires the public default constructor but
that is never called; instead another constructor is used at DataGrid.AddingNewItem.
I'd like to tell developers that the default constructor is not for their use.
Is there an attribute which suits the purpose?
I had checked DebuggerNonUserCode and MethodImplAttribute with MethodImplAttributes.InternalCall but not sure that's the proper approach.
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.dataGrid1.CanUserAddRows = true;
var list = new List<RowX>();
this.dataGrid1.ItemsSource = CollectionViewSource.GetDefaultView(list);
this.dataGrid1.AddingNewItem += (s, e) => e.NewItem = new RowX("ABC");
}
}
public class RowX
{
public RowX()
{
//this is not used. but CollectionView require this to be public or
//CanUserAddRows doesn't work.
}
public RowX(object o)
{
//this is the actual ctor.
}
public string Text { get; set; }
}
Mark it private
class Foo
{
private Foo() {}
}
You can give your constructor an access modifier.
private This means it can only be called from another constructor in that class.
public class PrivateClass
{
//Only from inside this class:
private PrivateClass()
{
}
public static PrivateClass GetPrivateClass()
{
//This calls the private constructor so you can control exactly what happens
return new PrivateClass();
}
}
internal This means only code in the same assembly (i.e. from inside your library) can access it.
public class InternalClass
{
//Only from within the same assembly
internal InternalClass(string foo)
{
}
}

Access WPF Name properties in static method

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
}
}

Access to listbox in static method

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();
}
}

how to use interface in C#

Using C# .NET 4.0, Visual Studio 2010.
Well at the moment I'm looking into de-coupling of Classes and using interfaces.
I've implemented a Solution from another post to test if I could get it working but unfortunately I have never used an interface ever.
So here's the basics of what I have:
Form1:
partial class Form1 : InterfacePareto
{
public string myTest
{
get { return herpTxt.Text; }
set { herpTxt.Text = value; }
}
}
Interface:
interface InterfacePareto
{
string myTest { get; set; }
}
MyWorkingOutClass:
Class MyWorkingOutClass
{
private readonly InterfacePareto pare;
public MyWorkingOutClass(InterfacePareto pare)
{
this.pare = pare;
}
private void Testtime()
{
string firstName = pare.myTest;
pare.myTest = firstName + " extra";
}
}
The purpose:
The plan at the moment is to get the text from the forms textbox. Then pass it to the working class. The working class then does whatever calculations etc needed, then passes the result back to the forms textbox.
My question is, is my code along the right tracks. If yes, then what am I missing/doing wrong? Or if anyone thinks this is not the right way of achieving what I need, do they have any suggestions?
Many thanks!
I've just tested code and this works fine for me:
public partial class MainForm :Form, InterfacePareto //My main form inheriting Form class and interface
{
public MainForm()
{
InitializeComponent();
}
public string myTest
{
get { return herpTxt.Text; }
set { herpTxt.Text = value; }
}
private void button1_Click(object sender, EventArgs e)
{
//On button click create MyWorkingOutClass instance and pass MainForms instance
MyWorkingOutClass mc = new MyWorkingOutClass(this);
//After this line text box content will change
mc.Testtime();
}
}
//Changed modifier to public
public interface InterfacePareto
{
string myTest { get; set; }
}
//Changed modifier to public
public class MyWorkingOutClass
{
private readonly InterfacePareto pare;
public MyWorkingOutClass(InterfacePareto pare)
{
this.pare = pare;
}
//Changed modifier to public
public void Testtime()
{
string firstName = pare.myTest;
pare.myTest = firstName + " extra";
}
}
This should work fine.
There is one issue you will get when the MyWorkingOutClass does its work on a different thread than the UI thread.
To solve that you might want to change the implementation on the form to switch to the UI thread.

How to call a method in FORM class from another class but both are same namespace

class Form1 : Form
{
public void enable()
{
//1st method which i want to call from another class
}
public void display()
{
//2nd method which i want to call from another class
}
}
class Buffer : signal
{
protected override Analyse()
{
//from here i want to call two functions in form class
}
}
this is how my code looks like anyone please reply this tread.........
When creating the Buffer class, you have to pass reference to the real instance of Form1 then just use that instance. Sample code:
class Form1 : Form
{
public void InitBuffer()
{
Buffer b = new Buffer(this);
...
}
public void enable()
{
//1st method which i want to call from another class
}
public void display()
{
//2nd method which i want to call from another class
}
}
class Buffer : signal
{
private Form1 form;
public Buffer(Form1 parent)
{
form = parent;
}
protected override Analyse()
{
form.enable();
form.display();
}
}
You can't grab the true instance of Form1 just like that out of nowhere.

Categories

Resources