Updated to be more clear….
I have a main form, Form1, and an additional class, AslLib. Form1 contains a method that updates a dataGridView control it contains. A method in AslLib calls this method.
My problem is that the only way I can make AslLib call Form1‘s method is by creating an instance of Form1 in AslLib‘s calling method like so:
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);
}
}
I have tried passing parameters in both the constructor and the method, but because (i think) the makeRequest method is static, the compiler is giving errors:
AsyncURLChecker.AslLib._form: cannot declare instance members in a static class AsyncURLChecker
Static classes cannot have instance constructors AsyncURLChecker
The result of the above is that the Console.WriteLine(status); part of Form1‘s method correctly outputs status, but the dataGridView does not change.
My belief is that because I am creating a new instance of Form1, I am no longer referencing the original Form1 containing my dataGridView, rather an entirely new copy, so it is not changing.
Can anyone tell me how I might manipulate the original Form1’s dataGridView from another class? My preferred method would be to call a Form1 method that updates dataGridView rather than directly accessing dataGridGiew from AslLib if possible.
You should pass reference to existing form instead of creating new one: