大家好,今天老師要我們作出如下圖的結果
但我目前只能做到這樣
以下是我的程式碼
SqlConnection conn = null;
SqlCommand command = null;
private void button1_Click(object sender, EventArgs e)
{
using (conn = new SqlConnection("Data Source=.;Initial Catalog=Northwind;Integrated Security=True"))
{
using (SqlCommand command = new SqlCommand("select *from Customers", conn))
{
conn.Open();
using (SqlDataReader datareader = command.ExecuteReader())
{
using (DataTable dataTable = new DataTable())
{
dataTable.Load(datareader);
this.dataGridView2.DataSource = dataTable;
}
}
}
}
}
private void button2_Click(object sender, EventArgs e)
{
categoriesTableAdapter1.Fill(northwindDataSet1.Categories);
dataGridView1.DataSource = northwindDataSet1.Categories;
}
private void tabPage1_Click(object sender, EventArgs e)
{
}
private void dataGridView2_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void button3_Click(object sender, EventArgs e)
{
try
{
using (conn = new SqlConnection("Data Source=.;Initial Catalog=Northwind;Integrated Security=True"))
{
conn.Open();
using (SqlCommand command = new SqlCommand("select *from Customers", conn))
{
using (SqlDataReader datareader = command.ExecuteReader())
{
//TreeNode tree = new TreeNode();
//while (datareader.Read())
//{
// treeView1.Nodes.Add(new TreeNode(datareader["Country"].ToString()));
//}
for (int i = 0; i < dataGridView2.Rows.Count; i++)
{
int rowindex = i + 1;
TreeNode node = new TreeNode("Row_" + rowindex);
for (int j = 0; j < dataGridView2.Columns.Count; j++)
{
node.Nodes.Add(dataGridView2.Rows[i].Cells[j].Value.ToString());
}
treeView1.Nodes.Add(node);
}
}
}
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
想請問有甚麼辦法可以做到我們老師要的結果,希望能給我一個方向,謝謝
你的Case裡面樹狀結構中分兩層,第一層是國家,第二層是城市
你應該下兩個select,第一個把國家層的node整理出來
第二個select才依每筆資料中所屬的城市放到第一層node底下
建議問問題的時候把問題描述清楚一點,右邊datagridview的功能只能用猜的
看起來應該是在點擊樹狀結構的node時直接select相關資料
所以點擊第一層時要select by country
點擊第二層的時候要select by city
再把select的結果放到datagridview就好
//(原)
using (SqlCommand command = new SqlCommand("select *from Customers", conn))
//(更)
using (SqlCommand command = new SqlCommand("select TOP 1 * from Customers", conn))
其實你再給多一點資料,例如:有條件WHERE什麼的。