How to add row to datagridview situated on another form

有些话、适合烂在心里 提交于 2019-12-11 16:19:19

问题


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?


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/9477151/how-to-add-row-to-datagridview-situated-on-another-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!