繁体   English   中英

从另一个类中的已保存变量将项目添加到dvv(C#winForms)

[英]Add items to a dgv from saved variables in another class (C# winForms)

我对编程和学习仍然比较陌生。 我刚刚制作了一个计算器,然后我想到了要保存两个输入数字(值1,值2)并将结果保存在另一个winform中的datagridview中的想法。 首先,我添加了一个按钮(bSave)进行保存。 我的第一次尝试是:dgvSavedResults.Rows.Add(tbValue1.Text,tbValue2.Text,tbResult.Text);“,并且工作正常。

我的下一个尝试是将所有内容保存在另一个类中:

public class Information
{
    private string value1;
    private string value2;
    private string result;

    public string Value1
    {
        get { return value1; }
        set { value1 = value; }
    }

    public string Value2
    {
        get { return value2; }
        set { value2 = value; }
    }

    public string Result
    {
        get { return result; }
        set { result = value; }
    }
}

在计算器形式中,当我单击“保存”按钮时,它看起来像这样:

    private void bSave_Click(object sender, EventArgs e)
    {
        Information info = new Information();
        info.Value1 = tbTal1.Text;
        info.Value2 = tbTal2.Text;
        info.Result = tbResultat.Text;                        
    }

我认为我需要使用数据表和信息类内部的循环。 但是我真的不知道如何使这项工作。 我已经四处搜寻,但是还没有找到我所了解的东西。 我在正确的轨道上吗? 还是我的想法完全错误? 如果有人能花时间向我解释该怎么做,并向我展示一个示例如何做,将不胜感激。 谢谢

您可以列出结果:

BindingList<Information> resultsList = new BindingList<Information>();

使用BindingSource将其绑定到DataGridView:

BindingSource resultsBindingSource = new BindingSource();

this.resultsBindingSource.DataSource = resultsList;
this.dgvSavedResults.DataSource = this.resultsBindingSource ;

然后:

private void bSave_Click(object sender, EventArgs e)
    {
        Information info = new Information();
        info.Value1 = tbTal1.Text;
        info.Value2 = tbTal2.Text;
        info.Result = tbResultat.Text;     
        resultsList.Add(info);                   
    }

完成了。

另外,根据要添加列的方式,您可以手动执行操作,也可以从Information类的公共属性自动生成它:

dgvSavedResults.AutoGenerateColumns=true;

编辑:

为了正确反映datagridview上的更改,最好使用BindingList而不是List

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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