using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace _2
{
public partial class KnowledgeTree : Form
{
private string connectionString = "Data Source=localhost;Initial Catalog=学习笔记管理;Integrated Security=True;";
// 声明控件变量
private SplitContainer mainSplitContainer;
private TreeView treeView;
private TextBox txtName1;
private TextBox txtSubject1;
private RichTextBox txtContent1;
private int currentPointId = -1; // 跟踪当前编辑的知识点ID
public KnowledgeTree()
{
InitializeComponent();
InitializeUI(); // 添加初始化调用
LoadKnowledgeTree(); // 添加树加载
}
// 初始化界面控件
private void InitializeUI()
{
{
// 主分割容器
mainSplitContainer = new SplitContainer
{
Dock = DockStyle.Fill,
SplitterDistance = 300,
Orientation = Orientation.Vertical // 明确分割方向
};
this.Controls.Add(mainSplitContainer);
// 树视图
treeView = new TreeView
{
Dock = DockStyle.Fill,
ImageList = CreateImageList(),
ShowNodeToolTips = true
};
mainSplitContainer.Panel1.Controls.Add(treeView);
// 详情面板
Panel detailPanel = new Panel { Dock = DockStyle.Fill };
mainSplitContainer.Panel2.Controls.Add(detailPanel);
// 详情控件
txtName = new TextBox { Location = new Point(10, 30), Width = 200 };
txtSubject = new TextBox { Location = new Point(10, 70), Width = 200 };
txtContent = new RichTextBox { Location = new Point(10, 110), Size = new Size(400, 200) };
btnSave = new Button { Text = "保存", Location = new Point(10, 320) };
btnSave.Click += SaveKnowledge; // 绑定保存事件
detailPanel.Controls.AddRange(new Control[] {
new Label { Text = "名称", Location = new Point(10, 10) },
txtName1,
new Label { Text = "学科", Location = new Point(10, 50) },
txtSubject,
new Label { Text = "内容", Location = new Point(10, 90) },
txtContent1,
btnSave
});
}
}
private ImageList CreateImageList()
{
ImageList images = new ImageList();
images.ColorDepth = ColorDepth.Depth32Bit;
images.ImageSize = new Size(24, 24);
// 使用系统图标(实际应用中应使用自定义图标)
images.Images.Add(SystemIcons.Information); // 0: 普通节点
images.Images.Add(SystemIcons.Warning); // 1: 重要节点
images.Images.Add(SystemIcons.Question); // 2: 问题节点
return images;
}
// 加载知识点树状图
private void LoadKnowledgeTree()
{
if (treeView == null) return;
treeView.Nodes.Clear();
treeView.BeginUpdate();
try
{
// 获取所有知识点
DataTable points = GetKnowledgePoints();
// 创建节点字典
var nodeDict = new Dictionary<int, TreeNode>();
// 第一遍:创建所有节点
foreach (DataRow row in points.Rows)
{
int pid = Convert.ToInt32(row["Pid"]);
string nodeText = $"{row["Pname"]} ({row["Stype"]})";
TreeNode node = new TreeNode(nodeText)
{
Name = pid.ToString(),
Tag = row, // 存储整行数据
ToolTipText = row["Content"].ToString(),
ImageIndex = GetNodeIconIndex(row["Stype"].ToString())
};
nodeDict.Add(pid, node);
}
// 第二遍:建立父子关系
foreach (DataRow row in points.Rows)
{
int pid = Convert.ToInt32(row["Pid"]);
object parentObj = row["ParentId"];
if (parentObj != DBNull.Value)
{
int parentId = Convert.ToInt32(parentObj);
if (nodeDict.ContainsKey(parentId))
nodeDict[parentId].Nodes.Add(nodeDict[pid]);
}
else
{
treeView.Nodes.Add(nodeDict[pid]);
}
}
// 展开所有节点
treeView.ExpandAll();
// 添加节点选择事件
treeView.AfterSelect += (s, e) => DisplayPointDetails(e.Node);
}
catch (Exception ex)
{
MessageBox.Show($"加载树失败: {ex.Message}");
}
finally
{
treeView.EndUpdate();
}
}
private int GetNodeIconIndex(string v)
{
// 简单示例:根据学科类型返回不同图标
return stype switch
{
"数学" => 0,
"物理" => 1,
"化学" => 2,
_ => 0
};
}
// 从数据库获取知识点
private DataTable GetKnowledgePoints()
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
// 确保关系表存在
EnsureRelationsTableExists(conn);
// 修复表名引用:Point -> PointNote
string sql = @"SELECT
p.Pid,
p.Pname,
p.Stype,
p.Content,
r.ParentId
FROM PointNote p
LEFT JOIN Relations r ON p.Pid = r.ChildId";
using (var da = new SqlDataAdapter(sql, conn))
{
var dt = new DataTable();
da.Fill(dt);
return dt;
}
}
}
private void EnsureRelationsTableExists(SqlConnection conn)
{
// 修复表名引用:pointnote -> PointNote
string sql = @"
IF NOT EXISTS (SELECT * FROM sys.tables WHERE name = 'Relations')
BEGIN
CREATE TABLE Relations (
RelationId INT PRIMARY KEY IDENTITY,
ParentId INT NULL,
ChildId INT NOT NULL,
CONSTRAINT FK_Child_Point FOREIGN KEY (ChildId) REFERENCES PointNote(Pid)
)
END";
using (var cmd = new SqlCommand(sql, conn))
{
cmd.ExecuteNonQuery();
}
}
private void label1_Click(object sender, EventArgs e)
{
}
// 显示选中知识点的详情
private void DisplayPointDetails(TreeNode node)
{
if (node?.Tag == null) return;
DataRow row = (DataRow)node.Tag;
txtName.Text = row["Pname"].ToString();
txtSubject.Text = row["Stype"].ToString();
txtContent.Text = row["Content"].ToString();
currentPointId = Convert.ToInt32(row["Pid"]); // 设置当前编辑的ID
}
private void SaveKnowledge(object sender, EventArgs e)
{
if (string.IsNullOrWhiteSpace(txtName.Text))
{
MessageBox.Show("知识点名称不能为空");
return;
}
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
// 修复1: 插入到正确的表 PointNote
// 修复2: 支持更新已有知识点
string sql = currentPointId == -1 ?
@"INSERT INTO PointNote (Pname, Stype, Content)
VALUES (@name, @subject, @content);
SELECT SCOPE_IDENTITY();" :
@"UPDATE PointNote
SET Pname = @name, Stype = @subject, Content = @content
WHERE Pid = @id;
SELECT @id;";
using (var cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.AddWithValue("@name", txtName.Text);
cmd.Parameters.AddWithValue("@subject", txtSubject.Text);
cmd.Parameters.AddWithValue("@content", txtContent.Text);
if (currentPointId != -1)
cmd.Parameters.AddWithValue("@id", currentPointId);
try
{
int newId = Convert.ToInt32(cmd.ExecuteScalar());
MessageBox.Show($"保存成功! ID: {newId}");
LoadKnowledgeTree(); // 刷新树
currentPointId = newId; // 更新当前ID
}
catch (Exception ex)
{
MessageBox.Show($"保存失败: {ex.Message}");
}
}
}
}
}
报错一堆怎么改