Hi RPA,
There are two different event for Cell Click and Header Click.
You need to handle both the events as per your requirement.
For Cell Click the event is CellClick (DataGridViewCellEventArgs).
For Header Click the event is ColumnHeaderMouseClick (DataGridViewCellMouseEventArgs).
Check this example. Now please take its reference and correct your code.
C#
public Form1()
{
InitializeComponent();
BindGrid();
}
private void BindGrid()
{
string constring = ConfigurationManager.ConnectionStrings[1].ConnectionString;
using (SqlConnection con = new SqlConnection(constring))
{
using (SqlCommand cmd = new SqlCommand("SELECT Name,Country FROM Customers", con))
{
cmd.CommandType = CommandType.Text;
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
using (DataSet ds = new DataSet())
{
sda.Fill(ds);
spGrid.DataSource = ds.Tables[0];
spGrid.AllowUserToAddRows = false;
}
}
}
}
}
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex > -1)
{
if (string.IsNullOrEmpty(spGrid.CurrentRow.Cells[e.ColumnIndex].Value.ToString()))
{
MessageBox.Show("cell is free");
}
else
{
MessageBox.Show("cell is not free");
}
}
}
private void spGrid_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
if (string.IsNullOrEmpty(spGrid.CurrentRow.Cells[e.ColumnIndex].Value.ToString()))
{
MessageBox.Show("cell is free");
}
else
{
MessageBox.Show("cell is not free");
}
}
VB.Net
Public Sub New()
InitializeComponent()
BindGrid()
End Sub
Private Sub BindGrid()
Dim constring As String = ConfigurationManager.ConnectionStrings(1).ConnectionString
Using con As SqlConnection = New SqlConnection(constring)
Using cmd As SqlCommand = New SqlCommand("SELECT Name,Country FROM Customers", con)
cmd.CommandType = CommandType.Text
Using sda As SqlDataAdapter = New SqlDataAdapter(cmd)
Using ds As DataSet = New DataSet()
sda.Fill(ds)
spGrid.DataSource = ds.Tables(0)
spGrid.AllowUserToAddRows = False
End Using
End Using
End Using
End Using
End Sub
Private Sub dataGridView1_CellClick(ByVal sender As Object, ByVal e As DataGridViewCellEventArgs)
If e.RowIndex > -1 Then
If String.IsNullOrEmpty(spGrid.CurrentRow.Cells(e.ColumnIndex).Value.ToString()) Then
MessageBox.Show("cell is free")
Else
MessageBox.Show("cell is not free")
End If
End If
End Sub
Private Sub spGrid_ColumnHeaderMouseClick(ByVal sender As Object, ByVal e As DataGridViewCellMouseEventArgs)
If String.IsNullOrEmpty(spGrid.CurrentRow.Cells(e.ColumnIndex).Value.ToString()) Then
MessageBox.Show("cell is free")
Else
MessageBox.Show("cell is not free")
End If
End Sub
Screenshot
