如何防止DataGridView双击多次打开表单?

时间:2011-08-11 08:34:39

标签: c#

双击dataGridView单元格时,如何打开表单一次?

private void dataGridView1_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
{
    //string queryString = "SELECT id, thename, address,fax,mobile,email,website,notes FROM movie";
    int currentRow = int.Parse(e.RowIndex.ToString());
    try
    {
        string movieIDString = dataGridView1[0, currentRow].Value.ToString();
        movieIDInt = int.Parse(movieIDString);
    }
    catch (Exception ex) { }
    // edit button
    if (e.RowIndex != -1)
    {
        string id = dataGridView1[0, currentRow].Value.ToString();
        string thename = dataGridView1[1, currentRow].Value.ToString();
        string address = dataGridView1[2, currentRow].Value.ToString();
        string fax = dataGridView1[3, currentRow].Value.ToString();
        string mobile = dataGridView1[4, currentRow].Value.ToString();
        string email = dataGridView1[5, currentRow].Value.ToString();
        string website = dataGridView1[6, currentRow].Value.ToString();
        string notes = dataGridView1[7, currentRow].Value.ToString();

        Form4 f4 = new Form4();

        f4.id = movieIDInt;
        f4.thename = thename;
        f4.address = address;
        f4.fax = fax;
        f4.mobile = mobile;
        f4.email = email;
        f4.website = website;
        f4.notes = notes;


        f4.Show();
    }
}

这个代码每次单击一个dataGridView时打开一个表单,我想如果它被打开,d​​oubleClick将不再打开它

3 个答案:

答案 0 :(得分:1)

在form.cs中将其声明为全局变量

  bool isopened = false;

然后检查isopened variable

if (isopened == false)
            {
                FormInitialSettings();
                Form4 f4 = new Form4();

                f4.id = movieIDInt;
                f4.thename = thename;
                f4.address = address;
                f4.fax = fax;
                f4.mobile = mobile;
                f4.email = email;
                f4.website = website;
                f4.notes = notes;
                isopened = true;
                f4.Show();
            }

答案 1 :(得分:1)

将打开的表单保留在类字段中 例如而不是你的代码,调用这样的方法:

    Form4 f4 = null; // class field

    // call this method when cellMouseDoubleClick is triggered
    private void OpenForm4IfNotOpened()
    {
        if (f4 == null || f4.IsDisposed)
        {
            f4 = new Form4();

            f4.id = movieIDInt;
            f4.thename = thename;
            f4.address = address;
            f4.fax = fax;
            f4.mobile = mobile;
            f4.email = email;
            f4.website = website;
            f4.notes = notes;
            f4.Show();
        }
        else
        {
            f4.BringToFront();
        }
    }

答案 2 :(得分:0)

最好的方法是使变量f4成为类级变量,而行Form4 f4 = new Form4();应该只运行一次,然后在行f4.Show();测试之前查看表单是否已经显示在尝试之前再次展示它。