簡體   English   中英

如何從另一個類訪問表單的方法以確保它是相同的Form實例-C#

[英]How to access a method of a form from another class ensuring it is the same Form instance - C#

更新以更加清晰。

我有一個主窗體Form1和一個附加類AslLib Form1包含一種更新其包含的dataGridView控件的方法。 AslLib的方法稱為此方法。

我的問題是,使AslLib調用Form1方法的唯一方法是在AslLib的調用方法中創建Form1的實例,如下所示:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    public void updateDataGUI(int row, string url, string status, long time)
    {
        Console.WriteLine(status);
        foreach (DataGridViewRow dgvr in dataGridView1.Rows) dgvr.Cells[0].Value = status;
    }

}



static class AslLib
{
    public static async void makeRequest(string url, int row )
    {
        string result;
        Stopwatch sw = new Stopwatch(); sw.Start();

        try
        {
            using (HttpClient client = new HttpClient())
            {
                HttpResponseMessage response = new HttpResponseMessage();
                response = await client.GetAsync(url);

                if (response.IsSuccessStatusCode)
                {
                    result = ((int)response.StatusCode).ToString();
                }
                else
                {
                    result = ((int)response.StatusCode).ToString();
                }
            }
        }
        catch (HttpRequestException hre)
        {
            result = "Server unreachable";
        }

        sw.Stop();
        long time = sw.ElapsedTicks / (Stopwatch.Frequency / (1000L * 1000L));


        _form.updateDataGUI(row, url, result, time);

    }
}

我嘗試過在構造函數和方法中傳遞參數,但是由於( 我認為makeRequest方法是靜態的,因此編譯器給出了錯誤:

AsyncURLChecker.AslLib._form: cannot declare instance members in a static class              AsyncURLChecker
Static classes cannot have instance constructors                AsyncURLChecker

上面的結果是Console.WriteLine(status); Form1的方法的一部分正確地輸出status ,但dataGridView不會更改。

我的信念是,因為我正在創建Form1的新實例,所以我不再引用包含我的dataGridView的原始Form1 ,而是一個全新的副本,因此它不會更改。

誰能告訴我如何從另一個類操縱原始Form1的dataGridView 我的首選方法是調用Form1方法來更新dataGridView而不是盡可能地直接從AslLib訪問dataGridGiew

您應該傳遞對現有表單的引用,而不是創建新表單:

// on Form1
Class1 c1 = new Class1();
c1.DoSomething(this);

// Class1
public void DoSomething(Form1 form)
{
    form.updateDataGUI(row, url, result, time);
}

將表單傳遞給類構造函數

private Form1 _form;
public Class1(Form1 form)
{
    _form = form;
}

現在,您可以從班級內部訪問表單。

您需要擁有MainForm的原始創建實例。 這是一種訪問方式:

Application.OpenForms.OfType<MainForm>().First().updateDataGUI(row, url, result, time);

Application.OpenForms包含當前正在運行的應用程序的所有打開的窗體。)

但是最好以可以將MainForm對象的引用傳遞給類的方式重新設計類結構。 另一種選擇是將實例保存在MainForm本身的靜態屬性中(如果您確定任何時候都只有一個實例)。

我想你可以用這個。

MainForm f = (MainForm)this.Owner;
f.updateDataGUI(row, url, result, time);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM