Hi satabeach,
The DataGridView does not support the expand / collapse (+/-).
You have to use DataGrid, which is replaced by the DataGridView.
The expand / collapse (+/-) buttons work only with two related DataTables in a DataSet.
Check this example. Now please take its reference and correct your code.
Database
For this example I have used of Northwind database that you can download using the link given below.
Download Northwind Database
Namespaces
C#
using System.Data;
using System.Data.SqlClient;
VB.Net
Imports System.Data
Imports System.Data.SqlClient
Code
C#
private void Form1_Load(object sender, EventArgs e)
{
DataTable dtCategories = GetData("SELECT CategoryID AS Id,CategoryName AS Name,Description FROM Categories");
DataTable dtProducts = GetData(@"SELECT CategoryID AS Id,ProductName AS Name,CAST(UnitPrice AS NUMERIC(18,2)) AS Price
FROM (SELECT *,ROW_NUMBER() OVER(PARTITION BY CategoryID ORDER BY ProductName DESC) AS Row_No FROM Products)
t WHERE Row_No <= 5");
DataSet ds = new DataSet();
ds.Tables.Add(dtCategories);
ds.Tables.Add(dtProducts);
DataRelation Datatablerelation = new DataRelation("Products", ds.Tables[0].Columns["Id"], ds.Tables[1].Columns["Id"], true);
ds.Relations.Add(Datatablerelation);
dataGrid1.DataSource = ds.Tables[0];
}
private DataTable GetData(string query)
{
string conString = "Server=.;DataBase=Northwind;UID=sa;PWD=pass@123";
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlCommand cmd = new SqlCommand(query, con))
{
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
return dt;
}
}
}
}
}
VB.Net
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim dtCategories As DataTable = GetData("SELECT CategoryID AS Id,CategoryName AS Name,Description FROM Categories")
Dim dtProducts As DataTable = GetData("SELECT CategoryID AS Id,ProductName AS Name,CAST(UnitPrice AS NUMERIC(18,2)) AS Price
FROM (SELECT *,ROW_NUMBER() OVER(PARTITION BY CategoryID ORDER BY ProductName DESC) AS Row_No FROM Products)
t WHERE Row_No <= 5")
Dim ds As DataSet = New DataSet()
ds.Tables.Add(dtCategories)
ds.Tables.Add(dtProducts)
Dim Datatablerelation As DataRelation = New DataRelation("Products", ds.Tables(0).Columns("Id"), ds.Tables(1).Columns("Id"), True)
ds.Relations.Add(Datatablerelation)
dataGrid1.DataSource = ds.Tables(0)
End Sub
Private Function GetData(ByVal query As String) As DataTable
Dim conString As String = "Server=.;DataBase=Northwind;UID=sa;PWD=pass@123"
Using con As SqlConnection = New SqlConnection(conString)
Using cmd As SqlCommand = New SqlCommand(query, con)
Using sda As SqlDataAdapter = New SqlDataAdapter(cmd)
Using dt As DataTable = New DataTable()
sda.Fill(dt)
Return dt
End Using
End Using
End Using
End Using
End Function
Screenshot
Note: Add the DataGrid control if not present to by right clicking the toolbar then Choose Items. From the .Net Framework Components tab add DataGrid.