简体   繁体   中英

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?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM