bragin.www
bragin.www

Reputation: 199

How to add row to datagridview situated on another form

i have two form applictaion. and i have datagrid with three string columns on the "MainForm". the destination of the second form is to add rows to this datagrid with some parametres such as text of the 1,2 and 3 columnns

this code works

private void MainForm_Load(object sender, EventArgs e)
{
  dgvTasks.Rows.Add("s1", "s2", "s3");
}

but when i drop this code to another form it doesn't work

//"MainForm"
public void addRowToDataGridView(string type, string title, string time)
{
  dgvTasks.Rows.Add(type, title, time);
}

//"ParametersForm"
public static MainForm fm = new MainForm();
private void btnSave_Click(object sender, EventArgs e)
{
  fm.addRowToDataGridView("s1", "s2", "s3");
}

no errors. just silent and rows don't add. can smb help me?

Upvotes: 0

Views: 2996

Answers (2)

mihai
mihai

Reputation: 2804

As I understand your question, i can suggest you such an answer

Make a property 'setter' in MainForm of any type (Ex: a

//here is your MainForm
{
    public List<MyGVContent> SetColumnHead
    {
           set
           {
                  //here call your method to whom give 'value' as parameter
                  //attention, that in value contains items with Type, Title, Time
                  addRowToDataGridView();
           }
    }
    //which will update your 'dgvTasks' gridview
) 

//here is your Parameters Form
{
    private void btnSave_Click(object sender, EventArgs e)
    {
        //here call the property to whom send parameters
        this.MainForm.SetColumnHead = ...
    }
}

//where 
public sealed class MyGVContent
{
    string Type
    {
        get; set;
    }

    string Title
    {
        get; set;
    }

    string Time
    {
        get; set;
    }
}

Good luck.

Upvotes: 0

Sinan AKYAZICI
Sinan AKYAZICI

Reputation: 3952

MainForm fm = new MainForm();

This way , You created another MainForm when you create instance object for MainForm.

You should attain active MainForm. So you should hold the active MainForm instance.

//"MainForm"

public static MainForm MainFormRef { get; private set; }
public Form1()
{
    InitializeComponent();
    MainFormRef = this;
}

public void addRowToDataGridView(string type, string title, string time)
{
  dgvTasks.Rows.Add(type, title, time);
}


//"ParametersForm"
private void btnSave_Click(object sender, EventArgs e)
{
  var fm = MainForm.MainFormRef;
  fm.addRowToDataGridView("s1", "s2", "s3");
}

Upvotes: 2

Related Questions