I have made use of the following table Customers with the schema as follows.
I have already inserted few records in the table.
You can download database SQL from here.
I have added a DataGridView in form1 with CellContentClick event.
Namespaces
using System.Data.SqlClient;
using System.Configuration;
C#
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
BindGrid();
}
private void BindGrid()
{
string constring = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constring))
{
using (SqlCommand cmd = new SqlCommand("SELECT * FROM Customers", con))
{
cmd.CommandType = CommandType.Text;
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
dataGridView1.DataSource = dt;
}
}
}
}
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex > -1)
{
string cellValue = this.dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
string columnName = this.dataGridView1.Columns[e.ColumnIndex].HeaderText;
Form2 f2 = new Form2(columnName, cellValue);
f2.Show();
this.Hide();
}
}
}
In Form2 i have added a Label to show the column name and cell clicked value.
C#
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private string ColumnName { get; set; }
private string CellValue { get; set; }
public Form2(string columnName, string cellValue)
{
this.ColumnName = columnName;
this.CellValue = cellValue;
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
this.label1.Text = string.Format("ColumnName = {0} And Value = {1}", this.ColumnName, this.CellValue);
}
}
Screenshots