I have a problem when I want to save the data in the database. the exception is:
System.InvalidOperationException: 'DataColumn' Name_Faculty 'missing in DataTable' disconnGrid 'for SourceColumn' Name_Faculty '.'
public void fillGrid()
{
if (adoF2.ds.Tables["disconnGrid"] != null)
{
adoF2.ds.Tables["disconnGrid"].Clear(); // to get new update.
}
adoF2.da = new SqlDataAdapter("SELECT * FROM Students", adoF2.con1);
adoF2.da.Fill(adoF2.ds, "disconnGrid");
dataGridView1.DataSource = adoF2.ds.Tables["disconnGrid"];
}
public void fillCombo()
{
adoF2.da = new SqlDataAdapter("SELECT * FROM Faculty", adoF2.con1);
adoF2.da.Fill(adoF2.ds, "disconnCombo");
comboBox1.DataSource = adoF2.ds.Tables["disconnCombo"];
comboBox1.DisplayMember = adoF2.ds.Tables["disconnCombo"].Columns[1].ColumnName;
comboBox1.ValueMember = adoF2.ds.Tables["disconnCombo"].Columns[0].ColumnName; /* this column is a foreign key into 'Students' table*/
}
private void gestionStagiaire2_Load(object sender, EventArgs e)
{
fillGrid();
fillCombo();
}
// to add the new row in the dataTable[disconnGrid]
private void button1_Click(object sender, EventArgs e)
{
adoF2.row1 = adoF2.ds.Tables["disconnGrid"].NewRow();
adoF2.row1[0] = textID.Text;
adoF2.row1[1] = textName.Text;
adoF2.row1[2] = comboBox1.SelectedValue; // to get the value not what is diplayed on the UI of comboBox1.
for (int i = 0; i < adoF2.ds.Tables["disconnGrid"].Rows.Count; i++)
{
if (textID.Text == adoF2.ds.Tables["disconnGrid"].Rows[i].ToString())
{
MessageBox.Show("Sorry the students is existed", "Warning", MessageBoxButtons.OK);
return; // to avoid errors.
}
}
adoF2.ds.Tables["disconnGrid"].Rows.Add(adoF2.row1);
MessageBox.Show("The students has been added successfully", "info", MessageBoxButtons.OK,MessageBoxIcon.Information);
dataGridView1.DataSource = adoF2.ds.Tables["disconnGrid"]; // to get the newly update.
}
// to save the data into the database:
private void saveB_Click(object sender, EventArgs e)
{
adoF2.cmdbuilder = new SqlCommandBuilder(adoF2.da);
adoF2.da.Update(adoF2.ds.Tables["disconnGrid"]);
MessageBox.Show("Saving has been succeeded", "Info", MessageBoxButtons.OK);
}