views:

11

answers:

1

As the title say,

DataGridview.ScrollBars = Vertical;

Assume the vision of DataGridview can contain 4 rows, if the row comes to 6, it has a Vertical ScrollBar. But if click the ScrollBar, the program will crash. If we set the DataGridview.ScrollBars = None, no problem will happen.

public partial class visitorLeave : Form
{
    public visitorLeave()
    {
        InitializeComponent();
    }
    bool isWorkerStopped = false;
    bool clickstart = false;
    ManageEmployee me = null;

    Thread tr1;

    private void visitorLeave_Load(object sender, EventArgs e)
    {
        me = new ManageEmployee(10);
        dataGridView1.AutoGenerateColumns = false;
        dataGridView1.DataSource = me.DataSource;
        tr1 = new Thread(new ThreadStart(Add));
        tr1.IsBackground = true;
        tr1.Start();
    }

    void Add()
    {
        while (!isWorkerStopped)
        {
            if (clickstart)
            {
                me.AddEmployee(new EmployeeData("new" + DateTime.Now.Ticks.ToString(), "0", "0", "0", "0", "0", null));
                dataGridView1.DataSource = me.DataSource;
                dataGridView1.UpdateRowHeightInfo(0, true);
                clickstart = false;
            }
        }
    }

    private void button1_Click(object sender, EventArgs e)
    {
        clickstart = !clickstart;
    }
}
+1  A: 

It is one of the leaks in Windows Forms' debugging logic that tries to detect you using controls in a thread-unsafe manner. It cannot see you assigning the DataSource property in a thread other than the UI thread.

Use BackgroundWorker to implement your threaded logic. And use its RunworkerCompleted event handler to set the grid's DataSource property. Or use Control.Invoke if you prefer to keep your existing threading code.

Hans Passant
But I still have a question:I want a program ( or a thread) to add data to the datasource, and the MainProgram updates the datagridview. How can I make it?
Michael
There's no problem using a thread to add data to, say, a List<>. But binding it to the grid *must* happen on the main thread. This isn't a problem, retrieving the data is the expensive bit, binding isn't.
Hans Passant