为什么System.Data.DataRow类实例化时没有构造?

本文讲述在给煤矿员工培训时被问到C#中System.Data.DataRow类为何无构造函数。原因是使用构造函数实例化数据行时无法确定其结构,需由表结构确定,应使用dt.NewRow()创建,且.Net Framework很多地方都符合此逻辑。
以前用C#的时候早就知道了System.Data.DataRow类是没有构造函数的(智能提示无法显示),一直都没有考虑过是为什么?

今天给一个煤矿的员工做培训的时候,突然被问到这个问题,想到了(也许这时候才是激发人的潜能的时候,回答不出来多没面子呀,呵呵……red_smile.gif)。

其实很简单,因为在如果要使用构造函数实例化一个数据行时,根本无法确定该数据行的结构,需要由表的结构来确定行的结构。

所以不应该是:
None.gifSystem.Data.DataRow dr = new System.Data.DataRow();
None.gif

        而应该是:

       
None.gif System.Data.DataRow dr = dt.NewRow();        //dt是一个包含列集合的DataTable
None.gif

其实,.Net Framework中很多地方都能体现这一点,可以说是完全符合人的思维逻辑的。
using System; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; 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 WindowsFormsApp3 { public partial class Form4 : Form { string conStr = ConfigurationManager.ConnectionStrings["conStr"].ConnectionString; SqlConnection connection = null; SqlDataAdapter adapter = null; DataSet ds = null; public Form4() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { connection= new SqlConnection(conStr); adapter=new SqlDataAdapter("select * from studentscores",connection); ds= new DataSet(); adapter.Fill(ds, "studentscores"); dataGridView1.DataSource = ds.Tables["studentscores"]; } private void button2_Click(object sender, EventArgs e) { ds = new DataSet(); SqlCommandBuilder builder = new SqlCommandBuilder(adapter); DataRow r1 = ds.Tables["studentscores"].NewRow(); r1[0]=textBox1.Text; r1[1]=textBox2.Text; r1[2]=textBox3.Text; ds.Tables[0].Rows.Add(r1); adapter.Update(ds,"studentscores"); dataGridView1.DataSource = ds.Tables["studentscores"]; } private void button3_Click(object sender, EventArgs e) { ds = new DataSet(); SqlCommandBuilder builder=new SqlCommandBuilder(adapter); DataRowCollection rows = ds.Tables["studentscores"].Rows; DataRow row; for (int i = 0;i<rows.Count; i++) { row= rows[i]; if (row["num"].ToString() == textBox1.Text) { row["scores"]=textBox3.Text ; } } adapter.Update(ds,"studentscores"); dataGridView1.DataSource = ds.Tables["studentscores"]; } private void button4_Click(object sender, EventArgs e) { SqlCommandBuilder builder=new SqlCommandBuilder(adapter); DataRowCollection rows = ds.Tables["studentscores"].Rows; DataRow row; for(int i = 0; i<rows.Count; i++) { row= rows[i]; if (row["num"].ToString()==textBox1.Text) { row.Delete(); } } adapter.Update(ds,"studentscores"); dataGridView1.DataSource = ds.Tables["studentscores"]; } } }
05-10
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=pointnote;Integrated Security=True;"; public KnowledgeTree() { InitializeComponent(); } // 初始化界面控件 private void InitializeUI() { // 窗体设置 this.Text = "知识点树状图系统"; this.Size = new Size(900, 600); this.StartPosition = FormStartPosition.CenterScreen; } 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() { TreeView treeView = this.Controls[0] is SplitContainer sc ? (TreeView)sc.Panel1.Controls[0] : null; 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"]); int? parentId = row["ParentId"] as int?; if (parentId.HasValue && nodeDict.ContainsKey(parentId.Value)) { nodeDict[parentId.Value].Nodes.Add(nodeDict[pid]); } else { treeView.Nodes.Add(nodeDict[pid]); } } // 展开所有节点 treeView.ExpandAll(); // 添加节点选择事件 treeView.AfterSelect += (s, e) => DisplayPointDetails(e.Node); } finally { treeView.EndUpdate(); } } private int GetNodeIconIndex(string v) { throw new NotImplementedException(); } // 从数据库获取知识点 private DataTable GetKnowledgePoints() { using (SqlConnection conn = new SqlConnection(connectionString)) { conn.Open(); // 假设有ParentId字段表示父知识点(需修改表结构) string sql = @"SELECT p.Pid, p.Pname, p.Stype, p.Content, r.ParentId FROM pointnote p LEFT JOIN KnowledgeRelations r ON p.Pid = r.ChildId"; using (var da = new SqlDataAdapter(sql, conn)) { DataTable dt = new DataTable(); da.Fill(dt); return dt; } } } private void label1_Click(object sender, EventArgs e) { } // 显示选中知识点的详情 private void DisplayPointDetails(TreeNode node) { if (node?.Tag == null) return; DataRow row = (DataRow)node.Tag; Control detailPanel = ((SplitContainer)this.Controls[0]).Panel2; // 更新详情面板 detailPanel.Controls["txtName"].Text = row["Pname"].ToString(); detailPanel.Controls["txtSubject"].Text = row["Stype"].ToString(); ((RichTextBox)detailPanel.Controls["txtContent"]).Text = row["Content"].ToString(); } private void SaveKnowledge(object sender, EventArgs e) { Control detailPanel = ((SplitContainer)this.Controls[0]).Panel2; string name = detailPanel.Controls["txtName"].Text; string subject = detailPanel.Controls["txtSubject"].Text; string content = ((RichTextBox)detailPanel.Controls["txtContent"]).Text; if (string.IsNullOrWhiteSpace(name)) { MessageBox.Show("知识点名称不能为空"); return; } using (SqlConnection conn = new SqlConnection(connectionString)) { conn.Open(); // 插入新知识点 string sql = @"INSERT INTO pointnote (Pname, Stype, Content) VALUES (@name, @subject, @content); SELECT SCOPE_IDENTITY();"; using (var cmd = new SqlCommand(sql, conn)) { cmd.Parameters.AddWithValue("@name", name); cmd.Parameters.AddWithValue("@subject", subject); cmd.Parameters.AddWithValue("@content", content); try { int newId = Convert.ToInt32(cmd.ExecuteScalar()); MessageBox.Show($"知识点保存成功! ID: {newId}"); // 刷新树状图 LoadKnowledgeTree(); } catch (Exception ex) { MessageBox.Show($"保存失败: {ex.Message}"); } } } } } }报错:未连接实例
最新发布
07-05
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值