There are multiple child nodes coming from Database in Treeview. Also, there is a DataGridview.
I want that when I select/click any of the child node from TreeView, it should show the related data(of selected child node) in DataGridview from Database on "Page Load".
My current code is below, which only binds all the data in DataGridview and Treeview from Database:
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
BindGrid();
FillchildNode();
}
//shows all data from database in GridView
private void BindGrid()
{
string query = "SELECT trainNumber,stationFullName,stationType,arrival,departure,scope,trackinfo FROM Table1";
MySqlDataAdapter sda = new MySqlDataAdapter(query, con);
MySqlCommandBuilder cmd = new MySqlCommandBuilder(sda);
DataTable dt = new DataTable();
sda.Fill(dt);
//Set AutoGenerateColumns False
dataGridView1.AutoGenerateColumns = false;
//Set Columns Count
dataGridView1.ColumnCount = 7;
//Add Columns
dataGridView1.Columns[0].Name = "trainNumber";
dataGridView1.Columns[0].HeaderText = "Train No";
dataGridView1.Columns[0].DataPropertyName = "trainNumber";
dataGridView1.Columns[1].Name = "stationFullName";
dataGridView1.Columns[1].HeaderText = "Station Name";
dataGridView1.Columns[1].DataPropertyName = "stationFullName";
dataGridView1.Columns[2].Name = "stationType";
dataGridView1.Columns[2].HeaderText = "Station Type";
dataGridView1.Columns[2].DataPropertyName = "stationType";
dataGridView1.Columns[3].Name = "arrival";
dataGridView1.Columns[3].HeaderText = "Arrival";
dataGridView1.Columns[3].DataPropertyName = "arrival";
dataGridView1.Columns[4].Name = "departure";
dataGridView1.Columns[4].HeaderText = "Departure";
dataGridView1.Columns[4].DataPropertyName = "departure";
dataGridView1.Columns[5].Name = "scope";
dataGridView1.Columns[5].HeaderText = "Scope";
dataGridView1.Columns[5].DataPropertyName = "scope";
dataGridView1.Columns[6].Name = "trackinfo";
dataGridView1.Columns[6].HeaderText = "Track Info";
dataGridView1.Columns[6].DataPropertyName = "trackinfo";
dataGridView1.DataSource = dt;
}
//Bind the childnodes in Treeview from Database
protected void FillchildNode()
{
string query = "SELECT id FROM Table1";
try
{
MySqlDataAdapter adp = new MySqlDataAdapter(query, con);
DataTable dt = new DataTable();
adp.Fill(dt);
TreeNode node = new TreeNode("Train Id");
foreach (DataRow dr in dt.Rows)
{
//fills only childnode in Treeview
node.Nodes.Add(dr["id"].ToString());
}
treeView1.Nodes.Add(node);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
Application.ExitThread();
}
}
Please reply how to do that.