Link to home
Start Free TrialLog in
Avatar of j4jones
j4jones

asked on

Help with C# mult threaded sql binding

My goal with this program is create a class that accepts three arguments (sql statement, datagridview, db connection) and then executes the SQL command on another thread. I am having an issue when it comes to invoking the data grid. Shown below is my code.

namespace multThreadDB
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        NpgsqlConnection conn = new NpgsqlConnection();
       
        private void button1_Click(object sender, EventArgs e)
        {
            db1 d = new db1("select * from meter;", dataGridView1, conn);
            new Thread(new ThreadStart(d.fillGrid)).Start();
        }
    }

    public class db1
    {
        string sql;
        DataGridView grid;
        NpgsqlConnection conn;
        DataSet ds = new DataSet();
       

        public db1(string sql, DataGridView grid, NpgsqlConnection conn)
        {
            this.grid = grid;
            this.sql = sql;
            this.conn = conn;
        }

        public void fillGrid()
        {
            conn.Open();
            NpgsqlDataAdapter adapter = new NpgsqlDataAdapter(sql, conn);
            adapter.Fill(ds);
            SetResult(ds);
            conn.Close();
        }

        delegate void SetDataSetDelegate(DataSet parameter);

        void SetResult(DataSet ds)
        {
            try
            {
                if (!InvokeRequired)
                    grid.DataSource = ds.Tables[0];
                else
                    Invoke(new SetDataSetDelegate(SetResult), new object[] { ds });
            }
            catch { }
        }
    }
}

I receiving errors on the invoke lines. It seems the error is caused because i am invoking a control from another class? How can I fix this?

Thanks in advance!
ASKER CERTIFIED SOLUTION
Avatar of wdosanjos
wdosanjos
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial