• C# TreeView 控件的综合使用方法


    1、概述

        该篇文章开发使用的语言c#,环境visualstudio2010,sql数据库.主要内容包括:

    (1)treeView控件添加根节点、子节点的基本方法,节点的删除。

    (2)把treeView控件的节点数据保存到SQL数据包括中,把数据库数据表中的数据动态加载到treeView控件中,控件节点的递归删除(指的是递归删除数据表的数据)

    2、TreeView控件的基本用法

         为了演示相关方法、属性的用法,通过vs2010创建一个winform项目,在项目中添加一个窗体,其布局如图2-1所示

    图2-1

    其中TreeView控件的名称为:treeview1,文本框的名称为:txtNodeName,“添加根节点”按钮的名称为:btnAddRootNode,“添加子节点”按钮的名称为:btnAddSonNode,“删除选中节点”按钮的名称:btnDelete

    添加节点、删除节点的代码如下所示:

    2.1添加根节点

    private void btnAddRootNode_Click(object sender, EventArgs e)
    {
    //要添加的节点名称为空,即文本框是否为空
    if(string.IsNullOrEmpty(txtNodeName.Text.Trim()))
    {
    MessageBox.Show("要添加的节点名称不能为空!");
    return;
    }
    //添加根节点
    treeView1.Nodes.Add(txtNodeName.Text.Trim());
    txtNodeName.Text = "";
    }

    添加根节点代码

    复制代码
     1 private void btnAddRootNode_Click(object sender, EventArgs e)
     2   {
     3       //要添加的节点名称为空,即文本框是否为空
     4         if(string.IsNullOrEmpty(txtNodeName.Text.Trim()))
     5          {
     6              MessageBox.Show("要添加的节点名称不能为空!");
     7              return;
     8          }
     9             //添加根节点
    10             treeView1.Nodes.Add(txtNodeName.Text.Trim());
    11            txtNodeName.Text = "";
    12   }
    复制代码

    2.2添加子节点

    private void btnAddSonNode_Click(object sender, EventArgs e)
    {
    //要添加的节点名称为空,即文本框是否为空
    if (string.IsNullOrEmpty(txtNodeName.Text.Trim()))
    {
    MessageBox.Show("要添加的节点名称不能为空!");
    return;
    }
    if(treeView1.SelectedNode==null)
    {
    MessageBox.Show("请选择要添加子节点的节点!");
    return;
    } treeView1.SelectedNode.Nodes.Add(txtNodeName.Text.Trim());
    txtNodeName.Text = "";
    }

    添加子节点代码

    复制代码
     1 private void btnAddSonNode_Click(object sender, EventArgs e)
     2    {
     3        //要添加的节点名称为空,即文本框是否为空
     4         if (string.IsNullOrEmpty(txtNodeName.Text.Trim()))
     5          {
     6              MessageBox.Show("要添加的节点名称不能为空!");
     7               return;
     8          }
     9          if(treeView1.SelectedNode==null)
    10           {
    11              MessageBox.Show("请选择要添加子节点的节点!");
    12               return;
    13           }               treeView1.SelectedNode.Nodes.Add(txtNodeName.Text.Trim());
    14     txtNodeName.Text = "";
    15    }
    复制代码

    2.3删除选中节点

    private void btnDelete_Click(object sender, EventArgs e)
    {
    if (treeView1.SelectedNode == null)
    {
    MessageBox.Show("请选择要删除的节点!");
    return;
    }
    treeView1.SelectedNode.Remove();
    }

    删除选中节点代码

    复制代码
    1  private void btnDelete_Click(object sender, EventArgs e)
    2   {
    3       if (treeView1.SelectedNode == null)
    4          {
    5               MessageBox.Show("请选择要删除的节点!");
    6               return;
    7          }
    8             treeView1.SelectedNode.Remove();
    9   }
    复制代码

    3、TreeView控件在树形菜单中的应用

        Treeview在产品类别管理、部门管理等树状多级菜单中的应用,主要包括把树控件中的数据保存到SQL数据表中,把数据表中的数据动态加载到treeview控件中,以及删除控件节点及数据表中的数据。

    3.1数据表

    create table TreeTest
    (
     id int identity(1,1) primary key not null,//节点id
     nodeName nvarchar(50) not null,//节点名称
     parentId int not null//节点父id
    )
    create table TreeTest
    (
     id int identity(1,1) primary key not null,//节点id
     nodeName nvarchar(50) not null,//节点名称
     parentId int not null//节点父id
    )

    3.2把节点数据存储到数据表

        把treeView添加的节点信息存储到数据表,包括根节点、子节点,所用的窗体界面如图2-1所示,控件的名称保持不变,只是执行代码变了。

    private void btnAddRootNode_Click (object sender, EventArgs e)
    {
    if(string.IsNullOrEmpty(txtNodeName.Text.Trim()))
    {
    MessageBox.Show("请填写要添加的节点名称!");
    return;
    }
    string sql = "insert into TreeTest(nodeName,parentId) output inserted.id values"+"("+" "+"'"+ txtNodeName.Text.Trim()+"'"+","+"'"+0+"'"+")";
    int id = (int)sqlHelper.ExecuteScalar(sql);
    TreeNode node1 = new TreeNode();
    node1.Tag = id;//把自己的id存放在该节点tag对象里
    node1.Text = txtNodeName.Text.Trim();
    treeView1.Nodes.Add(node1);
    txtNodeName.Text = "";
    }

    添加根节点

    复制代码
     1  private void btnAddRootNode_Click (object sender, EventArgs e)
     2   {
     3         if(string.IsNullOrEmpty(txtNodeName.Text.Trim()))
     4          {
     5              MessageBox.Show("请填写要添加的节点名称!");
     6               return;
     7          }
     8   string sql = "insert into TreeTest(nodeName,parentId) output inserted.id values"+"("+" "+"'"+ txtNodeName.Text.Trim()+"'"+","+"'"+0+"'"+")";
     9             int id = (int)sqlHelper.ExecuteScalar(sql);
    10             TreeNode node1 = new TreeNode();
    11             node1.Tag = id;//把自己的id存放在该节点tag对象里
    12             node1.Text = txtNodeName.Text.Trim();
    13             treeView1.Nodes.Add(node1);
    14             txtNodeName.Text = "";
    15         }
    复制代码

    private void btnAddSonNode_Click (object sender, EventArgs e)
    {
    int id;
    if(string.IsNullOrEmpty(txtNodeName.Text.Trim()))
    {
    return;
    }
    if(treeView1.SelectedNode==null)
    {
    MessageBox.Show("请选择父节点");
    return;
    }
    id =(int)treeView1.SelectedNode.Tag;//获取父id
    string sql = "insert into TreeTest(nodeName,parentId) output inserted.id values"+"(" + " " + "'" + txtNodeName.Text.Trim() + "'" + "," + "'" + id + "'" + ")";
    int id1 = (int)sqlHelper.ExecuteScalar(sql);
    TreeNode node1 = new TreeNode();
    node1.Tag = id1;
    node1.Text = txtNodeName.Text.Trim();
    treeView1.SelectedNode.Nodes.Add(node1);
    txtNodeName.Text = "";
    }

    添加子节点

    复制代码
     1 private void btnAddSonNode_Click (object sender, EventArgs e)
     2    {
     3             int id;
     4             if(string.IsNullOrEmpty(txtNodeName.Text.Trim()))
     5             {
     6                 return;
     7             }
     8             if(treeView1.SelectedNode==null)
     9             {
    10                 MessageBox.Show("请选择父节点");
    11                 return;
    12             }
    13             id =(int)treeView1.SelectedNode.Tag;//获取父id
    14             string sql = "insert into TreeTest(nodeName,parentId) output inserted.id values"+"(" + " " + "'" + txtNodeName.Text.Trim() + "'" + "," + "'" + id + "'" + ")";
    15             int id1 = (int)sqlHelper.ExecuteScalar(sql);
    16             TreeNode node1 = new TreeNode();
    17             node1.Tag = id1;
    18             node1.Text = txtNodeName.Text.Trim();
    19             treeView1.SelectedNode.Nodes.Add(node1);
    20             txtNodeName.Text = "";
    21  }
    复制代码

    3.3动态加载数据

        把数据表中的数据动态加载到treeView控件中,在treeView所在窗体的load事件中加载,相应的代码如下所示

    private void Form3_Load(object sender, EventArgs e)
    {
    //加载数据,把数据加载到控件treeview1中
    setTreeView(treeView1, 0);
    }

    //调用的时候parentId以0值开始 setTreeView(treeView1, 0);
    private void setTreeView(TreeView tr1,int parentId)
    {
    string sql = "select * from TreeTest where parentId=" + parentId;
    DataTable ds= sqlHelper.ExecuteDataTable(sql);
    if (ds.Rows.Count > 0)
    {
    int pId = -1;
    foreach (DataRow row in ds.Rows)
    {
    TreeNode node = new TreeNode();
    node.Text = row["nodeName"].ToString();
    node.Tag = (int)row["id"];
    pId = (int)row["parentId"];
    if (pId == 0)
    {
    //添加根节点
    tr1.Nodes.Add(node);
    }
    else
    {
    //添加根节点之外的其他节点
    RefreshChildNode(tr1,node,pId);
    }
    //查找以node为父节点的子节点
    setTreeView(tr1,(int)node.Tag);

    }
    }

    }
    //处理根节点的子节点
    private void RefreshChildNode(TreeView tr1,TreeNode treeNode, int parentId)
    {
    foreach (TreeNode node in tr1.Nodes)
    {
    if((int)node.Tag==parentId)
    {
    node.Nodes.Add(treeNode);
    return;
    }else if (node.Nodes.Count > 0)
    {
    FindChildNode(node, treeNode, parentId);
    }
    }
    }

    //处理根节点的子节点的子节点
    private void FindChildNode(TreeNode tNode,TreeNode treeNode, int parentId)
    {
    foreach (TreeNode node in tNode.Nodes)
    {
    if ((int)node.Tag == parentId)
    {
    node.Nodes.Add(treeNode);
    return;
    }else if (node.Nodes.Count > 0)
    {
    FindChildNode(node,treeNode,parentId);
    }

    }

    }

    动态加载数据代码

    复制代码
     1 private void Form3_Load(object sender, EventArgs e)
     2  {      
     3      //加载数据,把数据加载到控件treeview1中   
     4      setTreeView(treeView1, 0);           
     5  }
     6 
     7  //调用的时候parentId以0值开始 setTreeView(treeView1, 0);
     8   private void setTreeView(TreeView tr1,int parentId)
     9  {
    10   string sql = "select * from TreeTest where parentId=" + parentId;
    11       DataTable ds= sqlHelper.ExecuteDataTable(sql);
    12        if (ds.Rows.Count > 0)
    13         {
    14                int pId = -1;
    15              foreach (DataRow row in ds.Rows)
    16                {
    17                     TreeNode node = new TreeNode();
    18                     node.Text = row["nodeName"].ToString();
    19                     node.Tag = (int)row["id"];
    20                     pId = (int)row["parentId"];
    21                     if (pId == 0)
    22                     {
    23                         //添加根节点
    24                         tr1.Nodes.Add(node);
    25                     }
    26                     else
    27                     {
    28                         //添加根节点之外的其他节点
    29                         RefreshChildNode(tr1,node,pId);
    30                     }
    31                     //查找以node为父节点的子节点
    32                     setTreeView(tr1,(int)node.Tag);
    33 
    34                 }
    35             }
    36 
    37    }
    38 //处理根节点的子节点
    39   private void RefreshChildNode(TreeView tr1,TreeNode treeNode, int parentId)
    40  {
    41          foreach (TreeNode node in tr1.Nodes)
    42             {
    43                 if((int)node.Tag==parentId)
    44                 {
    45                     node.Nodes.Add(treeNode);
    46                     return;
    47                 }else if (node.Nodes.Count > 0)
    48                 {
    49                     FindChildNode(node, treeNode,  parentId);
    50                 }
    51             }
    52  }
    53 
    54   //处理根节点的子节点的子节点
    55   private void FindChildNode(TreeNode  tNode,TreeNode treeNode, int parentId)
    56  {
    57          foreach (TreeNode node in tNode.Nodes)
    58           {
    59                 if ((int)node.Tag == parentId)
    60                 {
    61                     node.Nodes.Add(treeNode);
    62                     return;
    63                 }else if (node.Nodes.Count > 0)
    64                 {
    65                     FindChildNode(node,treeNode,parentId);
    66                 }
    67 
    68             }
    69 
    70 }
    复制代码

    3.4、递归删除节点,这里指的是递归删除节点在数据表中的信息

    private void btnDelete_Click(object sender, EventArgs e)
    {
    if(treeView1.SelectedNode==null)
    {
    MessageBox.Show("请选择要删除的节点!");
    return;
    }
    //选中节点的id,也是其子节点的parentId
    int id = (int)treeView1.SelectedNode.Tag;
    nodeDelete(id);//递归删除数据表中的数据
    treeView1.SelectedNode.Remove();//删除控件中的节点

    }
    //数据表中的数据的递归删除方法
    public void nodeDelete(int id)
    {
    string sql = "select * from TreeTest where parentId="+id;
    DataTable ds = sqlHelper.ExecuteDataTable(sql);
    if (ds.Rows.Count > 0)
    {
    //有子节点
    foreach(DataRow row in ds.Rows)
    {
    //先删除父节点
    string delete = "delete from TreeTest where id=" + id;
    int k = sqlHelper.ExecuteNonQuery(delete);
    //查找子节点,删除
    int id1 = (int)row["id"];
    nodeDelete(id1);
    }
    }
    else
    {
    //没有子节点
    string delete = "delete from TreeTest where id="+id;
    int k = sqlHelper.ExecuteNonQuery(delete);
    }
    }

    删除节点代码

    复制代码
     1  private void btnDelete_Click(object sender, EventArgs e)
     2    {
     3          if(treeView1.SelectedNode==null)
     4          {
     5                 MessageBox.Show("请选择要删除的节点!");
     6                 return;
     7            }
     8             //选中节点的id,也是其子节点的parentId
     9             int id = (int)treeView1.SelectedNode.Tag;
    10             nodeDelete(id);//递归删除数据表中的数据
    11             treeView1.SelectedNode.Remove();//删除控件中的节点
    12 
    13   }
    14    //数据表中的数据的递归删除方法
    15    public void nodeDelete(int id)
    16  {
    17             string sql = "select * from TreeTest where parentId="+id;
    18             DataTable ds = sqlHelper.ExecuteDataTable(sql);
    19             if (ds.Rows.Count > 0)
    20             {
    21                 //有子节点
    22                 foreach(DataRow row in ds.Rows)
    23                 {
    24                     //先删除父节点
    25                     string delete = "delete from TreeTest where id=" + id;
    26                     int k = sqlHelper.ExecuteNonQuery(delete);
    27                     //查找子节点,删除
    28                     int id1 = (int)row["id"];
    29                     nodeDelete(id1);
    30                 }
    31             }
    32             else
    33             { 
    34                //没有子节点
    35                 string delete = "delete from TreeTest where id="+id;
    36                 int k = sqlHelper.ExecuteNonQuery(delete);
    37             }
    38 }
    复制代码

    4、TreeView控件的右键操作

    TreeView控件的右键操作,需要两个winform窗体form3(图4-1),form4(图4-2),其中form3中放置treeview1控件,两个contextMenuStrip,contextMenuStrip1和contextMenuStrip2,

    form4用于弹出菜单 填写要添加节点名称

    图4-1

    图4-2

    contextMenuStrip1

    contextMenuStrip2

    4.1 Form4窗体的代码如下:

    public partial class Form4 : Form
    {
    public string nodeName
    {
    get { return textBox1.Text.Trim(); }
    }
    public Form4()
    {
    InitializeComponent();
    }

    private void btnCancel_Click(object sender, EventArgs e)
    {
    DialogResult = DialogResult.Cancel;
    }

    private void btnConfirm_Click(object sender, EventArgs e)
    {
    if(string.IsNullOrEmpty(textBox1.Text.Trim()))
    {
    MessageBox.Show("请填写节点名称!");
    return;
    }
    DialogResult = DialogResult.OK;
    }
    }

    form4窗体代码

    复制代码
     1 public partial class Form4 : Form
     2  {
     3         public string nodeName
     4         {
     5             get { return textBox1.Text.Trim(); }
     6         }
     7         public Form4()
     8         {
     9             InitializeComponent();
    10         }
    11 
    12         private void btnCancel_Click(object sender, EventArgs e)
    13         {
    14             DialogResult = DialogResult.Cancel;
    15         }
    16 
    17         private void btnConfirm_Click(object sender, EventArgs e)
    18         {
    19             if(string.IsNullOrEmpty(textBox1.Text.Trim()))
    20             {
    21                 MessageBox.Show("请填写节点名称!");
    22                 return;
    23             }
    24             DialogResult = DialogResult.OK;
    25         }
    26 }
    复制代码

    4.2 form3窗体的代码如下:

    public partial class Form3 : Form
    {
    public Form3()
    {
    InitializeComponent();
    }
    private void treeView1_MouseDown(object sender, MouseEventArgs e)
    {
    if(e.Button==MouseButtons.Right)
    {
    Point ClickPoint = new Point(e.X, e.Y);
    int x = e.X;
    int y = e.Y;
    TreeNode CurrentNode = treeView1.GetNodeAt(ClickPoint);
    if (CurrentNode is TreeNode)//判断你点的是不是一个节点
    {
    treeView1.SelectedNode = CurrentNode;
    CurrentNode.ContextMenuStrip = this.contextMenuStrip1;
    contextMenuStrip1.Show(MousePosition);
    }
    else
    {
    treeView1.ContextMenuStrip = this.contextMenuStrip2;
    contextMenuStrip2.Show(MousePosition);
    }
    }
    }

    private void 添加子节点ToolStripMenuItem_Click(object sender, EventArgs e)
    {
    Form4 f5 = new Form4();
    if (f5.ShowDialog() == DialogResult.OK)
    {
    treeView1.SelectedNode.Nodes.Add(f5.nodeName);
    }
    }

    private void 删除选中节点ToolStripMenuItem_Click(object sender, EventArgs e)
    {
    treeView1.SelectedNode.Remove();
    }

    private void 添加根节点ToolStripMenuItem1_Click(object sender, EventArgs e)
    {
    Form4 f4 = new Form4();
    if (f4.ShowDialog() == DialogResult.OK)
    {
    treeView1.Nodes.Add(f4.nodeName);
    }
    }

    private void 清空ToolStripMenuItem1_Click(object sender, EventArgs e)
    {
    treeView1.Nodes.Clear();
    }
    }

    form3窗体代码

    复制代码
     1 public partial class Form3 : Form
     2     {
     3         public Form3()
     4         {
     5             InitializeComponent();
     6         }
     7         private void treeView1_MouseDown(object sender, MouseEventArgs e)
     8         {
     9             if(e.Button==MouseButtons.Right)
    10             {
    11                 Point ClickPoint = new Point(e.X, e.Y);
    12                 int x = e.X;
    13                 int y = e.Y;
    14                 TreeNode CurrentNode = treeView1.GetNodeAt(ClickPoint);
    15                 if (CurrentNode is TreeNode)//判断你点的是不是一个节点
    16                 {               
    17                     treeView1.SelectedNode = CurrentNode;
    18                     CurrentNode.ContextMenuStrip = this.contextMenuStrip1;                    
    19                     contextMenuStrip1.Show(MousePosition);
    20                 }
    21                 else
    22                 {
    23                     treeView1.ContextMenuStrip = this.contextMenuStrip2;
    24                     contextMenuStrip2.Show(MousePosition);
    25                 }
    26             }
    27         }
    28 
    29         private void 添加子节点ToolStripMenuItem_Click(object sender, EventArgs e)
    30         {
    31             Form4 f5 = new Form4();
    32             if (f5.ShowDialog() == DialogResult.OK)
    33             {
    34               treeView1.SelectedNode.Nodes.Add(f5.nodeName);
    35             }
    36         }
    37 
    38         private void 删除选中节点ToolStripMenuItem_Click(object sender, EventArgs e)
    39         {
    40             treeView1.SelectedNode.Remove();
    41         }
    42 
    43         private void 添加根节点ToolStripMenuItem1_Click(object sender, EventArgs e)
    44         {
    45             Form4 f4 = new Form4();
    46             if (f4.ShowDialog() == DialogResult.OK)
    47             {
    48                 treeView1.Nodes.Add(f4.nodeName);
    49             }
    50         }
    51 
    52         private void 清空ToolStripMenuItem1_Click(object sender, EventArgs e)
    53         {
    54             treeView1.Nodes.Clear();
    55         }
    56     }
    复制代码

     4.3、示例中用到的sqlHelper.cs文件代码如下所示

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Data;
    using System.Data.SqlClient;
    using System.Windows.Forms;

    namespace CRMProject.DAL
    {
    class SqlHelper
    {
    static DataTable dtInfo = new DataTable();
    public static SqlConnection My_con; //定义一个sqlConnection类型的公共变量My_con,用于判断数据库是否连接成功


    public static readonly string connstr =
    ConfigurationManager.ConnectionStrings["dbconnstr"].ConnectionString;

    public static int ExecuteNonQuery(string cmdText,
    params SqlParameter[] parameters)
    {
    using (SqlConnection conn = new SqlConnection(connstr))
    {
    conn.Open();
    using (SqlCommand cmd = conn.CreateCommand())
    {
    cmd.CommandText = cmdText;
    cmd.CommandTimeout = 3000;
    cmd.Parameters.AddRange(parameters);
    return cmd.ExecuteNonQuery();
    }
    }
    }

    public static void dgrd_Connection(string strSql, DataGridView dgrd, int start, int pagesize, string tableName)
    {

    try
    {
    SqlDataAdapter adapter = new SqlDataAdapter(strSql, getcon());
    DataSet dataSet = new DataSet();
    adapter.Fill(dataSet, start, pagesize, tableName);
    dtInfo = dataSet.Tables[tableName];
    dgrd.DataSource = dataSet.Tables[tableName];
    dgrd.AllowUserToAddRows = false;

    }
    catch { }
    }

    public static SqlConnection getcon()
    {


    My_con = new SqlConnection(connstr); //用SqlConnection对象与指定的数据库相连接
    My_con.Open(); //打开数据库连接
    return My_con; //返回SqlConnection对象的信息


    }
    public static int Count(string strSql)
    {
    using (SqlConnection conn = new SqlConnection(connstr))
    {
    conn.Open();
    using (SqlCommand cmd = conn.CreateCommand())
    {
    try
    {
    cmd.CommandText = strSql;
    cmd.CommandTimeout = 3000;
    int n = int.Parse(cmd.ExecuteScalar().ToString());
    return n;

    }
    catch { return 0; }
    }
    }
    }
    public static object ExecuteScalar(string cmdText,
    params SqlParameter[] parameters)
    {
    using (SqlConnection conn = new SqlConnection(connstr))
    {
    conn.Open();
    using (SqlCommand cmd = conn.CreateCommand())
    {
    cmd.CommandText = cmdText;
    cmd.CommandTimeout = 3000;
    cmd.Parameters.AddRange(parameters);
    return cmd.ExecuteScalar();
    }
    }
    }

    public static DataTable ExecuteDataTable(string cmdText,
    params SqlParameter[] parameters)
    {
    using (SqlConnection conn = new SqlConnection(connstr))
    {
    conn.Open();
    using (SqlCommand cmd = conn.CreateCommand())
    {
    cmd.CommandText = cmdText;
    cmd.CommandTimeout = 3000;
    cmd.Parameters.AddRange(parameters);
    using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))
    {
    DataTable dt = new DataTable();
    adapter.Fill(dt);
    return dt;
    }
    }
    }
    }

    public static SqlDataReader ExecuteDataReader(string cmdText,
    params SqlParameter[] parameters)
    {
    SqlConnection conn = new SqlConnection(connstr);
    conn.Open();
    using (SqlCommand cmd = conn.CreateCommand())
    {
    cmd.CommandText = cmdText;
    cmd.CommandTimeout = 3000;
    cmd.Parameters.AddRange(parameters);
    return cmd.ExecuteReader(CommandBehavior.CloseConnection);
    }
    }
    }
    }

    sqlhelper.cs

    复制代码
      1 using System;
      2 using System.Collections.Generic;
      3 using System.Linq;
      4 using System.Text;
      5 using System.Data;
      6 using System.Data.SqlClient;
      7 using System.Windows.Forms;
      8 
      9 namespace CRMProject.DAL
     10 {
     11     class SqlHelper
     12     {
     13         static DataTable  dtInfo = new DataTable();    
     14         public static SqlConnection My_con;  //定义一个sqlConnection类型的公共变量My_con,用于判断数据库是否连接成功
     15 
     16 
     17         public static readonly string connstr = 
     18             ConfigurationManager.ConnectionStrings["dbconnstr"].ConnectionString;
     19 
     20  public static int ExecuteNonQuery(string cmdText,
     21             params SqlParameter[] parameters)
     22         {
     23             using (SqlConnection conn = new SqlConnection(connstr))
     24             {
     25                 conn.Open();
     26                 using (SqlCommand cmd = conn.CreateCommand())
     27                 {
     28                     cmd.CommandText = cmdText;
     29                     cmd.CommandTimeout = 3000;
     30                     cmd.Parameters.AddRange(parameters);
     31                     return cmd.ExecuteNonQuery();
     32                 }
     33             }
     34         }
     35 
     36   public static void dgrd_Connection(string strSql, DataGridView dgrd, int start, int pagesize, string tableName)
     37         {
     38 
     39             try
     40             {
     41                 SqlDataAdapter adapter = new SqlDataAdapter(strSql, getcon());
     42                 DataSet dataSet = new DataSet();
     43                 adapter.Fill(dataSet, start, pagesize, tableName);
     44                 dtInfo = dataSet.Tables[tableName];
     45                 dgrd.DataSource = dataSet.Tables[tableName];
     46                 dgrd.AllowUserToAddRows = false;
     47 
     48             }
     49             catch { }
     50         }
     51 
     52         public static SqlConnection getcon()
     53         {
     54 
     55 
     56             My_con = new SqlConnection(connstr);   //用SqlConnection对象与指定的数据库相连接
     57             My_con.Open();  //打开数据库连接
     58             return My_con;  //返回SqlConnection对象的信息              
     59 
     60 
     61         }
     62         public static int Count(string strSql)
     63         {
     64             using (SqlConnection conn = new SqlConnection(connstr))
     65             {
     66                 conn.Open();
     67                 using (SqlCommand cmd = conn.CreateCommand())
     68                 {
     69                     try
     70                     {
     71                         cmd.CommandText = strSql;
     72                         cmd.CommandTimeout = 3000;
     73                         int n = int.Parse(cmd.ExecuteScalar().ToString());
     74                         return n;
     75 
     76                     }
     77                     catch { return 0; }
     78                 }
     79             }
     80         }
     81         public static object ExecuteScalar(string cmdText,
     82             params SqlParameter[] parameters)
     83         {
     84             using (SqlConnection conn = new SqlConnection(connstr))
     85             {
     86                 conn.Open();
     87                 using (SqlCommand cmd = conn.CreateCommand())
     88                 {
     89                     cmd.CommandText = cmdText;
     90                     cmd.CommandTimeout = 3000;
     91                     cmd.Parameters.AddRange(parameters);
     92                     return cmd.ExecuteScalar();
     93                 }
     94             }
     95         }
     96 
     97         public static DataTable ExecuteDataTable(string cmdText,
     98             params SqlParameter[] parameters)
     99         {
    100             using (SqlConnection conn = new SqlConnection(connstr))
    101             {
    102                 conn.Open();
    103                 using (SqlCommand cmd = conn.CreateCommand())
    104                 {
    105                     cmd.CommandText = cmdText;
    106                     cmd.CommandTimeout = 3000;
    107                     cmd.Parameters.AddRange(parameters);
    108                     using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))
    109                     {
    110                         DataTable dt = new DataTable();
    111                         adapter.Fill(dt);
    112                         return dt;
    113                     }
    114                 }
    115             }
    116         }
    117 
    118         public static SqlDataReader ExecuteDataReader(string cmdText,
    119             params SqlParameter[] parameters)
    120         {
    121             SqlConnection conn = new SqlConnection(connstr);
    122             conn.Open();
    123             using (SqlCommand cmd = conn.CreateCommand())
    124             {
    125                 cmd.CommandText = cmdText;
    126                 cmd.CommandTimeout = 3000;
    127                 cmd.Parameters.AddRange(parameters);
    128                 return cmd.ExecuteReader(CommandBehavior.CloseConnection);
    129             }
    130         }
    131     }
    132 }
    复制代码

     5、源码下载地址

    链接:http://pan.baidu.com/s/1mi5DGi0 密码:t22u

  • 相关阅读:
    PHP获取今天、昨天、明天的日期
    PHP使用Apache中的ab测试网站的压力性能
    php 数组操作
    ajax实时获取下拉数据
    php微信支付测试开发(流程已通)
    微信支付调用JSAPI缺少参数:timeStamp
    JS dom最常用API
    Javascript刷新页面的几种方法
    php+mysql 安全
    隐式的类类型转换
  • 原文地址:https://www.cnblogs.com/wwwbdabc/p/11652558.html
Copyright © 2020-2023  润新知