just got a slight problem here with updating a MySql DataGridView from visual studio in C#. The code below contains the fillData(); method that populates the datagrid. The Exception error is thrown in the button code. The aim of the button is to replace the Reviewed field from 0 to 1, meaning that the reviewed checkbox is then selected. This is probably a very basic problem so i may ask more questions, hope you can help.
public DataTable tb = new DataTable();
public MySqlDataAdapter a = new MySqlDataAdapter();
public void fillData()
{
using (MySqlConnection c = new MySqlConnection("host="";user="";password=""; database="";"))
{
c.Open();
string strSQL = "SELECT DataID, Date, WhichMeal, HbA1C_Test, Carbohydrates, GlucoseReading, InsulinUsed, InsulinType, ReviewedBy, Reviewed From PatientData WHERE username = '" + uname.Text + "';";
using (MySqlDataAdapter a = new MySqlDataAdapter(strSQL, c))
{
a.Fill(tb);
dataGridView2.DataSource = tb;
}
private void button5_Click(object sender, EventArgs e)
{
using (MySqlConnection c = new MySqlConnection("host=;user=;password= ""; database=""))
{
try
{
string DataId = dataGridView2.Rows[this.dataGridView2.SelectedRows[0].Index].Cells["DataID"].Value.ToString();
string Update = string.Format("UPDATE PatientData SET Reviewed = 1 WHERE DataID = {0}", DataId);
MySqlCommand command = new MySqlCommand(Update, c);
c.Open();
command.ExecuteNonQuery();
c.Close();
tb.Clear();
fillData();
}
catch (MySqlException ex)
{
MessageBox.Show(ex.ToString());
}
}
}
You can find the problem, by checking the following things:
this.dataGridView2.SelectedRows?this.dataGridView2.Rows?this.dataGridView2.SelectedRows[0].Index?Index value is greater than the valid number of entries in one of those collecions.