简体   繁体   中英

What is the best way to update datagridview?

I use below code to update datagridview in my application with Timmer. Timmer runs in everysecond and it keeps the screen flashing. How can i change not to flash at the time? or another way to update datagridview?

        SqlConnection mySqlConnection = new SqlConnection(SQLCONN);
        mySqlConnection.Open();

        SqlDataAdapter addapter = new SqlDataAdapter();
        DataTable dt = new DataTable("SSReportAmalgamate");
        SqlCommand cmd = mySqlConnection.CreateCommand();

        cmd.CommandText = "EXEC App_GetDATA " + "@acc" + "," + "@selecttype";
        cmd.Parameters.Add("@acc", SqlDbType.Char).Value = acc;
        cmd.Parameters.Add("@selecttype", SqlDbType.Char).Value = type;
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.CommandType = CommandType.Text;
        cmd.Connection = mySqlConnection;
        addapter.SelectCommand = cmd;

        addapter.Fill(dt);
        dataGridView1.DataSource = dt;

        mySqlConnection.Close();

The problem is, that you update the form even the data has not been changed. Instead, try to hear to an event from the SQL Server eg using a SqlDependency when there is new data (of course, if your data changes not often).

One course of action, assuming you're using WinForms, is to set the control to double buffer .

control.DoubleBuffered = true;

Or you can set that via the Properties window in Design view; the Form itself also has this property, IIRC.

And this...

[...] can reduce or eliminate flicker that is caused by progressive redrawing of parts of a displayed surface. Buffered graphics require that the updated graphics data is first written to a buffer. The data in the graphics buffer is then quickly written to displayed surface memory. The relatively quick switch of the displayed graphics memory typically reduces the flicker that can otherwise occur.

Add double buffering for the datagrid using extension method and later set it true in your form.

public static class ExtensionMethods
{
    public static void DoubleBuffered(this DataGridView dgv, bool setting)
    {
        Type dgvType = dgv.GetType();
        PropertyInfo pi = dgvType.GetProperty("DoubleBuffered",
            BindingFlags.Instance | BindingFlags.NonPublic);
        pi.SetValue(dgv, setting, null);
    }
}

Add the above class to your project and set double buffered property for the datagrid, like this

dataGridView1.DoubleBuffered(true);

Reference: http://bitmatic.com/c/fixing-a-slow-scrolling-datagridview

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM