Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

Clickable DataGridView

4.00/5 (1 vote)
2 May 2010CPOL 11.8K  
Download GridDetailsView.zip - 143.06 KBIntroductionThis is one of the frequently asked question among developer community.How to display a form which shows content of a DagaridView row while clicking on it. Here I am demonstrating DataGridViewLink column type usage for this...
Download GridDetailsView.zip - 143.06 KB

Introduction

This is one of the frequently asked question among developer community.How to display a form which shows content of a DagaridView row while clicking on it. Here I am demonstrating DataGridViewLink column type usage for this purpose.

Using the code
First Bind your data source to data grid though form designer or through code.

like this:

// Add datasource to datagrid	
this.datagridview1.DataSource =this.dbDataSet.Tables["person"].DeafultView;

While using form designer for binding data, go to datagridview properties->columns then change the type to DataGridViewLinkColumn.

Using code, it can be done like this. Add below code in Form Load event like this:
private void Form1_Load(object sender, EventArgs e)
        {
            // TODO: This line of code loads data into the 'dbDataSet.Person' table. You can move, or remove it, as needed.
            this.personTableAdapter.Fill(this.dbDataSet.Person);
            DataGridViewLinkColumn Column1 = new DataGridViewLinkColumn();
            Column1.DataPropertyName = "URLColumn";
            Column1.HeaderText = "Link";
            this.dataGridView1.Columns.Add(Column1);

        }

Subscribe to DataGridViewCellClick event and get data from current row.
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            DataTable ds = this.dbDataSet.Tables["person"];

            Form2 fm2 = new Form2(ds.Rows[e.RowIndex]["Name"].ToString(),
                ds.Rows[e.RowIndex]["Location"].ToString(),
                ds.Rows[e.RowIndex]["Age"].ToString());
            fm2.ShowDialog();
        }

pass data to child form using constructor
//Child form’s constructor
public Form2(string nameMain, string LocMain,string agemain)
        {
            InitializeComponent();
            this.name = nameMain;
            this.Loc = LocMain;
            this.age = agemain;
        }

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)