动态创建的datagridview单元格单击事件不起作用

时间:2012-12-19 06:33:41

标签: .net c#-4.0 datagridview

我正在动态创建dgv,我必须在其单元格点击上创建一个事件,我该怎么做? 现在,当我创建cellclick事件时,它什么也没有激发。

制作dgv的代码:

               dataGridView2 = new DataGridView();

                DataGridViewColumn col1 = new DataGridViewImageColumn
                {
                    ImageLayout = DataGridViewImageCellLayout.Stretch
                };

                DataGridViewColumn col2 = new DataGridViewImageColumn
                {
                    ImageLayout = DataGridViewImageCellLayout.Stretch
                };

                DataGridViewColumn col3 = new DataGridViewTextBoxColumn();
                DataGridViewColumn col4 = new DataGridViewLinkColumn();
                DataGridViewColumn col5 = new DataGridViewTextBoxColumn();
                DataGridViewColumn col6 = new DataGridViewTextBoxColumn();
                DataGridViewColumn col7 = new DataGridViewTextBoxColumn();

                col1.HeaderText = "TPM Image";
                col1.Name = "image_tpm";
                col1.Width = 60;

                col2.HeaderText = "Find Image";
                col2.Name = "image_thefind";
                col2.Width = 60;

                col3.HeaderText = "Name";
                col3.Name = "name";
                col3.Width = 150;

                col4.HeaderText = "URL";
                col4.Name = "product_url";
                col4.Width = 100;

                col5.HeaderText = "Price";
                col5.Name = "price";
                col5.Width = 70;

                col6.HeaderText = "Accuracy";
                col6.Name = "image_accuracy";
                col6.Width = 52;

                col7.HeaderText = "History";
                col7.Name = "history";
                col7.Width = 200;

                dataGridView2.Columns.Add(col1);
                dataGridView2.Columns.Add(col2);
                dataGridView2.Columns.Add(col3);
                dataGridView2.Columns.Add(col4);
                dataGridView2.Columns.Add(col5);
                dataGridView2.Columns.Add(col6);
                dataGridView2.Columns.Add(col7);

                dataGridView2.Location = new System.Drawing.Point(650, 20);
                dataGridView2.Size = new System.Drawing.Size(702, 413);
                this.Controls.Add(dataGridView2);

我的cellClickEvent

private void dataGridView2_CellClick(object sender, DataGridViewCellEventArgs e)
{
    try
    {
        if (dataGridView2.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString().Contains("http:"))
        {
            Process.Start(dataGridView2.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString());
        }
    }
    catch
    {
    }
}

但没有发生任何事情。

1 个答案:

答案 0 :(得分:5)

dataGridView2.CellClick += new DataGridViewCellEventHandler(dataGridView2_CellClick);

工作了。>:)