AfterCheck

        /// <summary>
/// 树勾选
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void tvCourse_AfterCheck(object sender, TreeViewEventArgs e)
{
if (e.Action ==TreeViewAction.ByMouse)
{
if (e.Node.Checked)
{
SetChildNode(e.Node, true);
if (null!= e.Node.Parent)
{
SetParentNode(e.Node, true);
}
//获取选中节点值
lstChapterIds.Add(e.Node.Name);
this.btnDelRes.Enabled = true;
}
else
{
//取消节点选中状态之后,取消所有父节点的选中状态
SetChildNode(e.Node, false);
//如果节点存在父节点,取消父节点的选中状态
if (e.Node.Parent != null)
{
SetParentNode(e.Node, false);
}
//获取选中节点值
if (lstChapterIds.Contains(e.Node.Name))
{
lstChapterIds.Remove(e.Node.Name);
if (!lstChapterIds.Any())
{
this.btnDelRes.Enabled = false;
}
}
} }
}

AfterCheck

设置节点

        /// <summary>
/// 查找根节点
/// </summary>
/// <param name="node">节点node</param>
/// <returns></returns>
private TreeNode FindParentNode(TreeNode node)
{
if (node.Parent == null)
{
return node;
}
else
{
return FindParentNode(node);
}
} /// <summary>
/// 设置父节点
/// </summary>
/// <param name="node">当前节点</param>
/// <param name="state">状态</param>
private void SetParentNode(TreeNode node, bool state)
{
TreeNode pNode = node.Parent;
if (null != pNode)
{
pNode.Checked = state;
bool flag = false;
foreach (TreeNode currNode in pNode.Nodes)
{
if (!currNode.Checked) //控制父节点全选,父节点选中去掉!
{
flag = false;
pNode.Checked = flag;
break;
}
//SetParentNode(item, state);
}
if (pNode.Checked )
{
//获取选中节点值
lstChapterIds.Add(pNode.Name);
}
else
{
if (lstChapterIds.Contains(pNode.Name))
{
lstChapterIds.Remove(pNode.Name);
}
}
SetParentNode(pNode, flag); }
}
/// <summary>
/// 设置子节点
/// </summary>
/// <param name="node">当前节点</param>
/// <param name="state">状态</param>
private void SetChildNode(TreeNode node, bool state)
{
TreeNodeCollection tncNodes = node.Nodes;
if (tncNodes.Count>)
{
foreach (TreeNode currNode in tncNodes)
{
currNode.Checked = state;
if (currNode.Checked)
{
//获取选中节点值
lstChapterIds.Add(currNode.Name);
}
else
{
if (lstChapterIds.Contains(currNode.Name))
{
lstChapterIds.Remove(currNode.Name);
}
} SetChildNode(currNode, state);
}
}
}

程序只开一个:program.cs

bool createdNew = false;
System.Threading.Mutex instance = new System.Threading.Mutex(true, Application.ProductName, out createdNew);
if (createdNew)
{
//...........code
instance.ReleaseMutex();
}
else
{
MessageBox.Show("该程序已经在运行!", Application.ProductName,MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
Application.Exit();
}

委托 不同线程间访问控件

private delegate void UploadPro(int mProgre);

private event UploadPro UploadProEvent;

UploadProEvent +=ResourceManage_UploadProEvent;

void ResourceManage_UploadProEvent(int mProgree)
{   //...... } var thread = new Thread(new ThreadStart(method));
thread.Start();

this.Invoke(UploadProEvent,currentPro);

解压缩 文件

ZipInputStream inputStream = new ZipInputStream(File.OpenRead(strFilePath));
ZipEntry theEntry;
//读取文件名
List<string> fileNameList = new List<string>();
while ((theEntry = inputStream.GetNextEntry()) != null)
{
totalSize += theEntry.UncompressedSize;
string templateName = theEntry.FileName;
string fileName = Path.GetFileName(templateName);
if (!string.IsNullOrEmpty(fileName))
fileNameList.Add(fileName);
}
inputStream.Close(); #region 解压文件 inputStream = new ZipInputStream(File.OpenRead(filePath));
//long totalSize = inputStream.Length;
long currentSize = ;
int currentPro = ;
ZipEntry theEntry;
ZipFile zf = ZipFile.Read(filePath);
//以文件流来解压所有文件,同时计算进度
while ((theEntry = inputStream.GetNextEntry()) != null)
{
//totalSize += theEntry.UncompressedSize;
//long totalSize = theEntry.UncompressedSize;
//destPath += "/";
//string templateName = theEntry.FileName;
//string fileName = Path.GetFileName(templateName);
////string dir = Path.GetDirectoryName(templateName);
//string dir = templateName;
//if (!dir.Contains("\\") && string.IsNullOrEmpty(fileName))
//{
// continue;
//}
////截取目录文件夹
//if (dir.Contains("\\"))
// dir = dir.Substring(dir.IndexOf("\\") + 1, dir.Length - dir.IndexOf("\\") - 1); //if (templateName.Length == (dir + "/" + fileName).Length) dir = ""; ////theEntry.IsDirectory 是否目录 //string path = Path.GetDirectoryName(destPath) + "/" + dir + "/";
////Path.GetDirectoryName(baseDir) + "/";//
//if (!Directory.Exists(path))
// Directory.CreateDirectory(path); string strFilePath = string.Empty;
string templateName = theEntry.FileName;
if (!templateName.Contains("\\"))
{
//文件
strFilePath = destPath + "\\" + theEntry.FileName;
}
else
{
//文件夹里文件
strFilePath = destPath + theEntry.FileName;
}
if (!Directory.Exists(Path.GetDirectoryName(strFilePath)))
{
Directory.CreateDirectory(Path.GetDirectoryName(strFilePath));
}
string fileName = Path.GetFileName(templateName);
if (fileName != String.Empty)
{
FileStream streamWriter = File.OpenWrite(strFilePath); //解压文件到指定的目录
int size = ;
byte[] data = new byte[];
try
{
while (true)
{
size = inputStream.Read(data, , data.Length);
if (size > )
{
streamWriter.Write(data, , size);
currentSize += size;
}
else
{
break;
}
currentPro = Convert.ToInt32( * currentSize / totalSize); this.Invoke(UploadProEvent,currentPro); }
}
catch (Exception ex)
{
LogHelper.Error(this.GetType(), ex);
this.Invoke(UploadProEvent, -); //-1 导入失败
}
finally
{
streamWriter.Close();
}
} }
inputStream.Close(); #endregion

检查指导文件盘符,获取空间大盘符

        /// <summary>
/// 检查指导盘符剩余空间
/// </summary>
/// <param name="str_HardDiskName"></param>
/// <returns></returns>
public static long GetHardDiskFreeSpace(string str_HardDiskName)
{
if (string.IsNullOrEmpty(str_HardDiskName)) return ; long freeSpace = new long();
System.IO.DriveInfo[] drives = System.IO.DriveInfo.GetDrives();
foreach (System.IO.DriveInfo drive in drives)
{
if (drive.Name == str_HardDiskName)
{
freeSpace = drive.TotalFreeSpace;
}
}
return freeSpace;
} /// <summary>
/// 找出当前客户端剩余空间最大盘符
/// </summary>
/// <returns></returns>
public static Dictionary<string, long> GetSystemDirtory()
{
Dictionary<string, long> freeSpace = new Dictionary<string, long>();
DriveInfo[] drives = DriveInfo.GetDrives();
foreach (DriveInfo drive in drives)
{
if (drive.DriveType == DriveType.Fixed)
freeSpace.Add(drive.Name, drive.TotalFreeSpace);
} string hardDiskName = freeSpace.ToArray().Max(x => x.Key);
long hardDiskSize = freeSpace.ToArray().Max(x => x.Value); freeSpace.Clear();
freeSpace.Add(hardDiskName, hardDiskSize); return freeSpace;
}

获取MAC地址

/// <summary>
/// 获取网卡MAC地址
/// </summary>
/// <returns></returns>
public static string GetNetCardMAC()
{
try
{
string stringMAC = "";
ManagementClass MC = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection MOC = MC.GetInstances();
foreach (ManagementObject MO in MOC)
{
if ((bool)MO["IPEnabled"] == true)
{
stringMAC += MO["MACAddress"].ToString(); }
}
return stringMAC;
}
catch
{
return "";
}
}

获取远程文件信息

        /// <summary>
/// 获取远程文件信息
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
public static RemoteFileInfo GetFileInfo(string url)
{
RemoteFileInfo result = new RemoteFileInfo(); try
{
GC.Collect();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
result.MimeType = response.ContentType;
result.LastModified = response.LastModified;
result.FileSize = response.ContentLength;
result.AcceptRanges = String.Compare(response.Headers["Accept-Ranges"], "bytes", true) == ; //关闭连接
response.Close();
request.KeepAlive = false;
}
catch (Exception ex)
{
throw;
} return result;
}

错误日志

       #region 日志方法
public void LogTest(string str)
{
string path = System.IO.Directory.GetCurrentDirectory() + "\\log\\";
if (!Directory.Exists(path))
{
DirectoryInfo directorylnfo = new DirectoryInfo(path);
directorylnfo.Create();
}
string dt = "\r\n时间:" + DateTime.Now.ToString("yyyymmddhhmmss") + "\r\n内容:" + str;
int len = dt.Length;
byte[] inputByts = new byte[len];
inputByts = Encoding.GetEncoding("utf-8").GetBytes(dt);
System.IO.FileStream fs = new System.IO.FileStream(path + "log.txt", System.IO.FileMode.OpenOrCreate);
fs.Seek(, System.IO.SeekOrigin.End);
fs.Write(inputByts, , inputByts.Length);
fs.Close();//关闭流
}
#endregion
        /// <summary>
/// 错误日志
/// </summary>
/// <param name="errorMsg"></param>
public static void WriteLog(Exception ex)
{
string logPath = GetResDir() + "/log";
string message = string.Format("\r\n\r\n异常时间:{0} \r\n错误源:{1} \r\n异常信息:{2}",
DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss,fff"), ex.Source, ex.Message);
File.AppendAllText(logPath + DateTime.Now.ToString("yyyy.MM.dd") + ".log", message, Encoding.UTF8);
}

启动停止服务

/// <summary>
/// 启动服务sc.DisplayName
/// </summary>
/// <param name="serverName"></param>
public static void StartService(string serverName)
{
if (string.IsNullOrEmpty(serverName)) return;
ServiceController sc = new ServiceController(serverName);
if (sc.DisplayName != null)
{
if (sc.Status == ServiceControllerStatus.Stopped) sc.Start();
}
} /// <summary>
/// 停止服务
/// </summary>
/// <param name="serverName"></param>
public static void StopService(string serverName)
{
if (string.IsNullOrEmpty(serverName)) return;
ServiceController sc = new ServiceController(serverName);
if (sc.DisplayName != null) {
if (sc.Status == ServiceControllerStatus.Running) sc.Stop();
}
}

插入修改表数据

       public string InsertORupdateData<T>(List<T> _list, string dtName,string columnName)
{
StringBuilder sbInsert = new StringBuilder(); ArrayList list = new ArrayList();
try
{
string sqlstr = "";
if (_list != null && _list.Count > )
{ System.Reflection.PropertyInfo[] p = _list[].GetType().GetProperties();
int length = ;
string values = ""; for (int i = ; i < _list.Count; i++)
{
string sbUpdateSql = "";
int count = ;
string upwh = "";
length = ;
//通过反射获取list中的字段
foreach (System.Reflection.PropertyInfo pi in p)
{ string cName = pi.Name;
string cValue = (pi.GetValue(_list[i], null) == null
? ""
: (pi.GetValue(_list[i], null)).ToString().Replace("'", "")); //替换 '语法错误的 if (cName.ToLower() == columnName.ToLower())
{
string sql = "select count(0) from " + dtName + " where " + columnName + "='"+cValue+"'";
upwh = " where " + columnName + "='" + cValue + "'";
count = ExcelHelper.GetScalar(sql);
} if (length == )
{
sqlstr = "INSERT INTO " + dtName + " (";
values = "(";
sbUpdateSql+="update " + dtName + " set ";
}
length += ;
if (length < p.Length)
{
sbUpdateSql += cName + "= '" + cValue +"',";
sqlstr += cName + ",";
values += "'" + cValue + "',";
}
else
{
sbUpdateSql += cName + "= '" + cValue + "'";
sqlstr += cName + ") Values";
values += "'" + cValue + "'); "; if (count > )
{
sqlstr = sbUpdateSql + upwh;
values = "";
}
}
}
sqlstr += values;
list.Add(sqlstr);
}
}
//for (int i = 0; i < list.Count; i++)
//{
// ArrayList arrList = new ArrayList();
// arrList.Add(list[i]);
// var result = AccessDbHelper.ExecuteSqlTran(arrList);
//}
//string str = string.Join("", list.ToArray());
var result = AccessDbHelper.ExecuteSqlTran(list);
return "success";
}
catch (Exception err)
{
LogTest(err.ToString());
return err.ToString();
} }

winfrom C#树勾选等的更多相关文章

  1. winfrom 树勾选

    树勾选 /// <summary> /// 树勾选 /// </summary> /// <param name="sender"></p ...

  2. Ext.js中树勾选的四种操作

    最近在做控件优化的时候产品提了一个需求,对树的勾选要满足四种勾选方案: 1.点击一次根节点,当根节点和子节点均未选中的情况下,根节点和子节点全都选中. 2.第二次点击根节点,当根节点和部分或全部子节点 ...

  3. Ext树控件第一次勾选父节点子节点没选中

    项目中同事提出了这样一个bug 问题: 第一次勾选父节点子节点竟然没选中,逆天了啊 初步分析: 可能是之前代码的逻辑错误造成的,随进入调试阶段... 调试中发现该参数为空(原来写代码的也太没素质了), ...

  4. Extjs改变树节点的勾选状态

    Extjs改变树节点的勾选状态 今天系统中有处地方需要一个功能点击一个按钮后将树节点前的复选框去掉,变成没有选择的状态.网上搜索了半天,然后自己查查API,终于找到解决办法了,下面把方法贴出来. 在E ...

  5. ztree学习---将默认勾选的展开

    这里只给出前台页面上的代码,数据可以从后台获取,注意,在封装数据的时候,注意:Id(节点的id,可以是数字也可以是字符串) , pid(父亲节点的id) , name(节点名称)不能少 . html页 ...

  6. 解决jquery操作checkbox全选全不选无法勾选问题

    最近在学习中使用jquery操作checkbox,使用下面方法进行全选.反选:$("input[name='checkbox']").attr("checked" ...

  7. 使用递归方法遍历TreeView的节点如配置则勾选

    自己在网上找了一段时间都没有找到取自数据库的值与TreeView中的节点值进行对比如匹配则勾选中CheckBox的资料,后面自己写了一个递归方法实现,现在记录起来以备需要时使用.在没写这递归方法前如果 ...

  8. Unity关于脚本前面的勾选框

    今天做项目时需要在某个事件条件下禁用某个脚本,但是突然发现这个脚本前面没有勾选框,,,就像这样 网上搜了下,原来是需要在脚本中加上void Start()方法,即使这个方法里什么都没有 void St ...

  9. zTree默认勾选指定ID并执行事件

    try { var arrs = $('#subjectClassID').val().split(","); var treeObj = $.fn.zTree.getZTreeO ...

随机推荐

  1. SQL server 提取字符中第一次和最后一次出现的数字

    CREATE FUNCTION [dbo].[StringExtractNumber(FirstOrLast)](@address nvarchar(max),@firstOrLast INT) re ...

  2. 动态合并或定制GridView控件Header头某些列

    开发时,有时会对GridView控件头做一些字段合并.多行表头,多列合并,明白了其中的原理,实现起来,均能运用自如.下面Insus.NET分享自己的做法. 创建站点,创建aspx网页,拉GridVie ...

  3. 利用PIL实现图片的切割

    功能描述: 切图前是一张图,切图后就是九张图!!! 展示: 实现流程图: 代码实现 # -*- coding: utf-8 -*- ''' 将一张图片填充为正方形后切为9张图 ''' from PIL ...

  4. 自定义非等高 Cell

    1.自定义非等高 Cell介绍 1.1 代码自定义(frame) 新建一个继承自 UITableViewCell 的类. 重写 initWithStyle:reuseIdentifier: 方法. 添 ...

  5. Serialization之SOAP序列化

    前言 XML序列化还可用于对象序列化符合SOAP规范的XML流.SOAP是一种简单的基于XML的协议,它使应用程序通过HTTP来交换信息.专门为使用XML来传输过程调用而设计的.如同常规的XML序列化 ...

  6. ThinkPHP CURD 操作

    Thinkphp CURD操作php中实例还对象即可操作 (目录) 1.Add 1 调式程序 3 调出显示页面Trace信息 3 Dump 的含义 4 2.数据库查询 4 1.直接使用字符串进行查找 ...

  7. 智能合约安全事故回顾(2)-BEC溢出攻击

    讲溢出攻击之前,先给大家讲个故事:2014年的时候,美国的宾夕法尼亚州的某个小镇上发生了一个乌龙事件,征兵系统对一万多名1893年到1897出生的男子发去信函,要求他们注册参军,否则面临罚款和监禁.收 ...

  8. 最优的cuda线程配置

    1 每个SM上面失少要有192个激活线程,寄存器写后读的数据依赖才能被掩盖   2 将 寄存器 的bank冲突降到最低,应尽量使每个block含有的线程数是64的倍数   3 block的数量应设置得 ...

  9. 二分图【洛谷P2175】 小Z的游戏分队

    P2175 小Z的游戏分队 小Z受不了寂寞,准备举办一次DOTA比赛,为了能让ACM班全部都参加比赛,他还特制了一张DOTA地图能够支持任意多人打任意多人. 现在问题来了,怎么把这么多人分成两队?小Z ...

  10. 树状数组【bzoj1782】: [Usaco2010 Feb]slowdown 慢慢游

    [bzoj1782]: [Usaco2010 Feb]slowdown 慢慢游 Description 每天Farmer John的N头奶牛(1 <= N <= 100000,编号1-N) ...