Reputation: 9184
How can i append data to my dataGridView on form, from another class?
here is class:
class TermSh
{
public HttpWebRequest request_get_page_with_captcha;
public HttpWebResponse response_get_page_with_captcha;
public string url;
public Form1 form1;
public BindingSource bindingSource1 = new BindingSource();
public int id = 0;
public TermSh(Form1 form1)
{
this.form1 = form1;
form1.dataGridView1.DataSource = bindingSource1;
}
public void somemethod()
{
try
{
cookies += response_get_page_with_captcha.Headers["Set-Cookie"];
bindingSource1.Add(new Log(id++, DateTime.Now, cookies));
form1.dataGridView1.Update();
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
and form class:
TermSh term_sh = new TermSh(this);
term_sh.somemethod();
what i do wrong? why my datagridview is empty after code executing, but with debug i see, that bindingSource1 is not empty. how to add data?
Upvotes: 0
Views: 1114
Reputation: 313
I think , the way you are going to achieve your goal is incorrect. first of all, I think passing Form class to a class is very very bad. and then you can simply manipulate a list and return the value and using this value (list) in your Form.
I think it's better to do like this: [EDIT 1] this following class, is your ptimary class that has a method and this method return a new Log, and you can add this return value to the datagridview in the Form1.
class TermSh
{
public HttpWebRequest request_get_page_with_captcha;
public HttpWebResponse response_get_page_with_captcha;
public string url;
public int id = 0;
public List<Log> somemethod()
{
try
{
cookies += response_get_page_with_captcha.Headers["Set-Cookie"];
return new Log(id++, DateTime.Now, cookies); //use this return value in your Form and update datagridview
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
}
[EDIT 2] after that: you must prepare Log Class to be used as a collection in bindingSource (Form1.bindingSource) and update gridView. and the Following code show the Log class:
class Log
{
private int id;
private DateTime datetime;
private string log_text;
public Log(int id, DateTime datetime, string log_text)
{
this.id = id;
this.datetime = datetime;
this.log_text = log_text;
}
#region properties
public int ID { get { return id; } set { id = value; } }
public DateTime DATE_TIME { get { return datetime; } set { datetime = value; } }
public string LOG_TEXT { get { return log_text; } set { log_text = value; } }
#endregion
}
[Edit 3] and this code in the Form1, use the return value of class TermSh, and populate the dataGridView:
TermSh term_sh = new TermSh(city, type, null, null);
logList.Add(term_sh.getPageWithCaptchaConnection());
logBindingSource.DataSource = logList;
logBindingSource.ResetBindings(false);
[EDIT 4] so if you have a question that : "how use this class as a collection in bindingSource??". It's simple, you can populate a dataGridView with objects: this article is helpful.
Upvotes: 2