0

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

这是我的表单代码 - 我遗漏了一些(希望不是必需的)部分: PS:注意我在 btnAddEntry_Click()-Method 末尾的评论

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();
    }
4

1 回答 1

1

由于这条线,您正在丢失最后一行的信息:(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);
    }
}
于 2013-06-27T05:57:59.910 回答