7
Answers

Add rows to a datagridview which is databound

Hennie Smit

Hennie Smit

13y
6.1k
1

Hi
I am creating a WinForm app and one form I have a dgv which is databound to a SQL database. I have almost got it figured out how to programatically add more roes to the dgv, but have some obstacles to overcome. The code below is from the event where everything happens.
It reads the RefRate_Acc table, filtered by Year, Month, Account. If any records are found, they are displayed in the dgv.
If none are found, then the ForexPairSelected table is read. Unique values are stored in a new datatable, and the dgv is populated with the values. The dgv may be populated with only one new record or as many as 25 new records, before the user makes any changes to the data.
This works 100% if only one record needs to ne inserted into the dgv.
However, I get an Index out of range error message on subsequent loops of the for statement.
What am I doing wrong?
 

private void btnSearch_Click(object sender, EventArgs e)
{
try
{
this.RefYear = int.Parse(this.cmbYear.Text.ToString());
this.RefMonth = int.Parse(this.cmbMonth.Text.ToString());
this.AccID = int.Parse(this.txtAccID.Text);
// TODO: This line of code loads data into the 'dsPortMan.RefRate_Acc' table.
// You can move, or remove it, as needed.
this.taRefRate_Acc.FillByAcc(this.dsPortMan.RefRate_Acc, this.RefYear, this.RefMonth, this.AccID);
this.rc = this.dsPortMan.RefRate_Acc.Count;
if (this.rc > 0)
{
this.taRefRate_Acc.FillByAcc(this.dsPortMan.RefRate_Acc, this.RefYear, this.RefMonth, this.AccID);
}
else
{
this.taForexPairSel.FillByAcc(this.dsPortMan.ForexPairSelection, this.AccID);
DataTable dtUniqueForex = this.dsPortMan.Tables["ForexPairSelection"].DefaultView.ToTable(true, "ForexPairID", "ForexPairCode");
this.cmbForexPairSelID.DataSource = dtUniqueForex;
this.cmbForexPairSelID.DisplayMember = "ForexPairID";
this.cmbForexPairSel.DataSource = dtUniqueForex;
this.cmbForexPairSel.DisplayMember = "ForexPairCode";
this.fp = dtUniqueForex.Rows.Count;
for (int i = 0; i < fp; i++)
{
this.dgvAccRefRate[1, i].Value = this.cmbYear.Text;
this.dgvAccRefRate[2, i].Value = this.cmbMonth.Text;
this.dgvAccRefRate[3, i].Value = this.txtAccID.Text;
this.dgvAccRefRate[4, i].Value = this.cmbAccount.Text;
this.dgvAccRefRate[5, i].Value = this.cmbForexPairSelID.Text;
this.dgvAccRefRate[6, i].Value = this.cmbForexPairSel.Text;
if (fp > 1)
{
this.dsPortMan.RefRate_Acc.NewRow();
this.dgvAccRefRate.Refresh();
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "An Error has occured", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
Answers (7)