程序添加的DataGridViewRow丢失

本文关键字:丢失 DataGridViewRow 添加 程序 | 更新日期: 2023-09-27 18:20:00

如主题中所述,我正在尝试向Datagridview添加一个新行。在表单的构造函数中,我将AllowUserToAddRows设置为false。我仍然可以以编程方式添加行,但它似乎没有保存在我的设置文件中。

这是我表格的代码——我遗漏了一些(希望不是必要的)部分:附言:请注意我在btAddEntry_Click()-方法末尾的评论

public DataSettings()
    {
        InitializeComponent();
        //Import rows that are saved int settings
        for (int i = 0; i < Properties.Settings.Default.colNames.Count; i++)
        {
            dgv.Rows.Add(new DataGridViewRow());
            dgv.Rows[i].Cells[0].Value = Properties.Settings.Default.colNames[i];
            dgv.Rows[i].Cells[1].Value = Properties.Settings.Default.colStarts[i];
            dgv.Rows[i].Cells[2].Value = Properties.Settings.Default.colWidths[i];
        }
        //Hide "new row"-row
        dgv.AllowUserToAddRows = false;
    }
    private void cancel_Click(object sender, EventArgs e)
    {
        this.Dispose();
    }
    private void save_Click(object sender, EventArgs e)
    {
        Properties.Settings.Default.colNames = new System.Collections.Specialized.StringCollection();
        Properties.Settings.Default.colStarts = new System.Collections.Specialized.StringCollection();
        Properties.Settings.Default.colWidths = new System.Collections.Specialized.StringCollection();
        foreach (DataGridViewRow row in dgv.Rows)
        {
            if (row.Index < dgv.Rows.Count - 1)
            {
                Properties.Settings.Default.colNames.Add((String)row.Cells[0].Value);
                Properties.Settings.Default.colStarts.Add((String)row.Cells[1].Value);
                Properties.Settings.Default.colWidths.Add((String)row.Cells[2].Value);
            }
        }
        Properties.Settings.Default.Save();
        this.DialogResult = DialogResult.OK;
    }
    private void btnAddEntry_Click(object sender, EventArgs e)
    {
        dgv.AllowUserToAddRows = true;
        Dialogs.Data_AddRow newRow = new Dialogs.Data_AddRow();
        newRow.ShowDialog();
        dgv.Rows.Add(new string[] { newRow.parmName, newRow.parmStart, newRow.parmWidth });
        newRow.Dispose();
        dgv.AllowUserToAddRows = false;  //If I comment out this line - It works fine.
                                         //but then the "newrow"-row is visible
    }
    private void btnDeleteEntry_Click(object sender, EventArgs e)
    {
        dgv.Rows.Remove(dgv.SelectedRows[0]);
    }
    private void btnDeleteAll_Click(object sender, EventArgs e)
    {
        dgv.Rows.Clear();
    }

程序添加的DataGridViewRow丢失

由于这一行,您正在丢失最后一行的信息:(row.Index < dgv.Rows.Count - 1)应该是(row.Index < dgv.Rows.Count),或者干脆去掉它。

如果您想在保存时检查最后一行是否不是NewRow,请执行以下操作:

foreach (DataGridViewRow row in dgv.Rows)
{
    if (!row.IsNewRow)
    {
        Properties.Settings.Default.colNames.Add((String)row.Cells[0].Value);
        Properties.Settings.Default.colStarts.Add((String)row.Cells[1].Value);
        Properties.Settings.Default.colWidths.Add((String)row.Cells[2].Value);
    }
}