如主题所述,我正在尝试向Datagridview添加新行。 在表单的构造函数中,我将AllowUserToAddRows设置为false。 我仍然能够以编程方式添加行,但它似乎没有保存在我的设置文件中。
这是我的表格代码 - 我留下了一些(希望不是必不可少的)部分: P.S。:在我的btnAddEntry_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();
}
答案 0 :(得分: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);
}
}