blade_blade
blade_blade

Reputation: 41

SQLite C# and DataGridView

I have problem if I try to fill datagridview with data if i call function from another form. Everything work perfect if i call function in private void button1_Click in form2 where is datagridview but if i call function from another form (Form1) datagridview is empty .

Code in Form2 where is datagridview

        public void fill_grid() {
        MessageBox.Show("Yuhuuuuuuu");
        form_Listusers form = new form_Listusers();
        SQLiteConnection cn = new SQLiteConnection(Form1.dbQuery); 
        cn.Open();
        string SQL;
        SQL = "SELECT users_id, name, username, place FROM users";
        SQLiteCommand cmd = new SQLiteCommand(SQL, cn);
        SQLiteDataAdapter da = new SQLiteDataAdapter(cmd);
        DataSet ds = new DataSet();
        try
        {
            da.Fill(ds);
            DataTable dt = ds.Tables[0];
            this.grid_userlist.DataSource = dt;

        }
        catch (Exception ex)
        {
            MessageBox.Show("Errrrrrrror");
        }
        cn.Close();

    }

Code in Form1 :

       Form2 frm = new Form2();
       frm.fill_grid();

I got Message "Yuhuuuuuuuu" but datagridview is empty.

#

SOLVED

#

In Main Form (Form1) i set instance

Form frm_Listusers = new form_Listusers(); 

but after this:

form_Listusers frm_Listusers = new form_Listusers();

i can access to my function frm.fill_grid();

Upvotes: 4

Views: 13315

Answers (2)

soheil bijavar
soheil bijavar

Reputation: 1213

change this `this.grid_userlist.DataSource = dt; to grid_userlist.DataSource = dt; and create instance from your second form class in another form then call methods of form2 for example

 form2 frm2 = new fomr2;
 frm2.fill_grid()

Upvotes: 0

lebrot
lebrot

Reputation: 21

when you run following code:

Form2 frm = new Form2();
frm.fill_grid();

You just create an instance of Form2, but the Form shown you is Form1. Then what happens is you see the DataGridView of Form1 that you did not fill it because you made this in Form2.

If you want to add the display of Form2 addition to Form1, add only the following line at the end:

frm.Show();

There are several ways to display the Form2, depending on the option you want (show only the Form2, show both, etc.).

About the message you see, it's because the line: MessageBox.Show ("Yuhuuuuuuu"); This event fires for all the application and does not depend on which form is displayed now.

Upvotes: 1

Related Questions