【问题标题】:Adding new entry to DataGridView via BindingSource通过 BindingSource 向 DataGridView 添加新条目
【发布时间】:2017-09-24 16:51:39
【问题描述】:

早安,

我现在正在编写一个 PasswordManager,并且一直在向我的 DataGridView 添加新行。

你可以在这里看到我的代码:PassMangaer

Engine/NewEntry.cs 包含用于创建新条目并将其添加到 BindingSource 的代码。 之后,PassManger/frmAddNewEntry.cs将其添加到主Form上的DataGridView中并刷新DataGridView。

实际上它只是用新行替换了当前行,并没有按预期添加新行。

我在这里错过了什么?

【问题讨论】:

    标签: c# winforms datagridview


    【解决方案1】:

    当您创建 BindingSource Bs = new BindingSource() 时,您在 frmAddNewEntry 第 18 行出现问题。 btnAddEntry_Click 适用于空 B。 我的建议:

    1. 通行证管理器。删除第 18 行
    2. public void addNewEntry(BindingSource bs, int id, string hoster)

    3. private void btnAddEntry_Click(object sender, EventArgs e) { 字符串主机 = textBox1.Text; ne.addNewEntry(mainForm.Bs, 1, hoster); mainForm.RefreshDGV(); this.Close(); }

    不建议使用,但对于您的最后一条评论,那将是快速修复:

            public void LoadData(DataGridView grid)
        {
            DataTable dataTable = new DataTable();
            foreach (DataGridViewColumn col in grid.Columns)
            {
                dataTable.Columns.Add(new DataColumn(col.Name));
            }
            string file = "mygrid.bin";
            using (BinaryReader bw = new BinaryReader(File.Open(file, FileMode.Open)))
            {
                int n = bw.ReadInt32();
                int m = bw.ReadInt32();
                for (int i = 0; i < m; ++i)
                {
                    dataTable.Rows.Add();
                    for (int j = 0; j < n; ++j)
                    {
                        if (bw.ReadBoolean())
                        {
                            dataTable.Rows[i][j] = bw.ReadString();
                            dataTable.Rows[i][j] = Base64Decode(dataTable.Rows[i][j].ToString());
                        }
                        else bw.ReadBoolean();
                    }
                }
            }
            grid.DataSource = dataTable;
        }
    

    【讨论】:

    • 感谢您的回答,但如果我删除第 18 行,如何传递实际的 BindingSource?
    • 好的,现在我有点困惑。我得到了你的新功能,这对我来说很有意义。但现在我得到一个 System.NullReferenceException:'对象引用未设置为对象的实例。 bs 为空。在 NewEntry.cs 中
    • 在方法中使用 mainForm.Bs 作为参数。告诉我你的 addNewEntry 以及你如何称呼它
    • 我更新了我的 Git:[link]github.com/Smarcy/PassManagerfrmAddNewEntry.cs 中的调用,NewEntry.cs 中的函数
    • public frmMain() { BS = new BindingSource();
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-12-12
    • 1970-01-01
    • 2016-07-24
    • 2018-05-13
    • 2012-06-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多