Search code examples
c#sqlwinformsbindingsourcetableadapter

BindingSource not moves to next record with MoveNext() after TableAdapter.Fill


I have this event on a button click below:

private void button4_Click(object sender, EventArgs e)
{
    string connectionString2 = "Data Source=LPMSW09000012JD\\SQLEXPRESS;Initial Catalog=Pharmacies;Integrated Security=True";
    string query2 = "UPDATE Liguanea_Lane2 SET Progress= '1' where code = '" + comboBox2.Text + "'; ";
    using (SqlConnection connection = new SqlConnection(connectionString2))
    {
        SqlCommand command = new SqlCommand(query2, connection);
        command.Connection.Open();
        command.ExecuteNonQuery();
    }
    comboBox2.ResetText();
    textBox1.Clear();
    comboBox2.SelectedIndex = comboBox2.SelectedIndex + 1;
    this.liguanea_Lane2TableAdapter.Fill(this.pharmaciesDataSet3.Liguanea_Lane2);
    liguaneaLane2BindingSource.MoveNext();
}

The problem is this particular block of code:

this.liguanea_Lane2TableAdapter.Fill(this.pharmaciesDataSet3.Liguanea_Lane2);
liguaneaLane2BindingSource.MoveNext();

Wha it is doing is basically refreshing the datasource within the data grid and move to the next item in the table. Eg.After the button is clicked it Updates the "progress" column value to "1" and then refresh the data set and then call the .MoveNext to move the cursor to the next item in the table. It works but only executes once and then stops moving. The dataset refreshes fine but the .MoveNext is the issue. I try moving it above the dataset but then it does not execute the problem. What am I doing wrong?


Solution

  • When you call TableAdapter.Fill(Table) it cause the BindingSource which is bind to Table moves to first record. So calling bindingSource.MoveNext() after filling the table always moves to second record.

    If for any reason you want to move to next record after filling the table using table adapter, store the current position before fill and set the position to next record after fill:

    int current = 0;
    private void Button1_Click(object sender, EventArgs e)
    {
        current = bindingSource1.Position;
        tableAdapter1.Fill(dataSet1.Table1);
        bindingSource1.Position = Math.Min(current + 1, bindingSource1.Count - 1);
    }