我将有一个带有一些节点的treenode。我的表单上会有一个datagridview。最初我会将一些数据加载到gridview中。现在,如果我在我的trreview中选择一个节点,我想将一个特定的行作为选定行。
假设我的树视图如下
根 | - >儿童 | - > Child1
如果我选择了child,我想在相应的行中选择相应的行,如果child1另一行应该被选中。
请知道
答案 0 :(得分:1)
1)您需要将节点映射到相应的数据网格行
this.dataGridView1.Rows[0].Tag = id; // a node id
2)处理节点点击事件并按ID找到相应的行并选择它
if (tvwACH.SelectedNode.Parent != null)
{
int id = (int)tvwACH.SelectedNode.Tag ; // make sure you've already assigned tag when creating Three nodes and data rows
foreach(DataGridViewRow row in this.dataGridView1.Rows)
{
int rowId = (int)row.Tag ;
if(rowId == id)
{
row.Selected = ture;
}
else
{
row.Selected = false; //discard other rows
}
}
}
答案 1 :(得分:0)
答案 2 :(得分:0)
这是我写的代码
private void tvwACH_AfterSelect(object sender, TreeViewEventArgs e)
{
string node = string.Empty;
if (tvwACH.SelectedNode.Parent != null)
{
node = tvwACH.SelectedNode.Text.ToString();
if (node == "FileHeader")
{
int tag = Convert.ToInt16(tvwACH.SelectedNode.Tag.ToString());
this.dataGridView1.Rows[0].Tag = tag;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
int rowId = (int)row.Tag;
if (rowId == tag)
{
row.Selected = true;
}
}
}
string strSwitch = tvwACH.SelectedNode.Parent.Text;
switch (strSwitch)
{
case "ACH":
{
dataGridView1.Visible = true;
dataGridView1.Rows.Clear();
node = tvwACH.SelectedNode.Text;
StreamReader sr = new StreamReader(node);
while (sr.Peek() >= 0)
{
string line = sr.ReadLine();
dataGridView1.Rows.Add(rectype[line.Substring(0, 1)].ToString(), line);
}
sr.Close();
}
break;
}
}
}
答案 3 :(得分:0)
试试这个:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
int flage = 1;
private void button1_Click(object sender, EventArgs e)
{
flage = 1;
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
if (dataGridView1.Rows[i].Selected)
{
DataGridViewRow currentRow = dataGridView1.SelectedRows[0];
TreeNode node1 = new TreeNode(currentRow.Cells[1].Value.ToString());
TreeNode node2 = new TreeNode(currentRow.Cells[2].Value.ToString());
TreeNode node3 = new TreeNode(currentRow.Cells[3].Value.ToString());
TreeNode[] TreeArray = new TreeNode[] { node1,node2, node3 };
TreeNode finalnode = new TreeNode(currentRow.Cells[0].Value.ToString(), TreeArray);
treeView1.Nodes.Add(finalnode);
flage = 1;
break;
}
else
{
flage = 0;
}
}
if(flage==0)
{
MessageBox.Show("Row is not Selected Please select the row");
}
}
private void button2_Click(object sender, EventArgs e)
{
treeView1.Nodes.Remove( treeView1.SelectedNode);
}
int flage2;
private void button3_Click(object sender, EventArgs e)
{
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
if (dataGridView1.Rows[i].Selected)
{
dataGridView1.Rows.Remove(dataGridView1.SelectedRows[0]);
flage2 = 1;
break;
}
else
{
flage2 = 0;
}
}
if (flage2 == 0)
{
MessageBox.Show("Row is not selected Please select the row");
}
}
}