.net常用功能函数说明

来源:互联网 发布:海岛奇兵铁矿升级数据 编辑:程序博客网 时间:2024/05/01 05:32

1、装箱拆箱

要判断原始类型是否是某个给定的原子类型,用is;如果要返回一个字符串,可以用object类的GetType方法。

 

2、注意ADONET中数据查询语句中的符号格式(c#实现)

  a.引号

  在查询时,出现单引号时,应将之替换为两个单引号,即name='K''Leey',我们在实际操作中,当数据查询语句中出现单引号时,可以使用String类的Replace方法进行替换将“'”换成“''”,如

  condition = "name='"+tempname.Replace("'","''")+"'"

    b.日期

  可以使用#符号来处理ADO.NET中涉及日期格式的查询,如下示例

  condition = "endDate<#2005/09/07# and endDate>#2005/08/07#"

   c.列分隔符

  当数据表中的某列由于某些原因含有列分隔符时,sale order,可以使用[]将此列区分开来,如下示例:condition = "[sale order] = S845647"

3、设计对话框

 添加 Windows 窗体, 在属性窗口中,将 FormBorderStyle 属性更改为 FixedDialog

根据需要自定义窗体的外观。 ControlBoxMinimizeBox MaximizeBox 属性设置为 false

设置按钮的DialogResult属性,可以将按钮设置为CancelOK等。

设置对话框的AcceptButtonCancelButton属性,可以将键盘的EnterEsc事件影射到

  相应得Button上去。

4、属性定义

  private string _Age;

 public int Age//注意没有括号,有返回值

  {           

set {_Age=value;}  

get {return _Age;}

 }

5Byte [] String 之间的转化

Encoding.Default.GetBytes(this.textBox2.Text)

Byte [] byteR2;

this.listBox1.Items.Add(Encoding.Default.GetString(byteR2));

6TreeViewSystem.Xml.XmlNode

     a、将Xml插入TreeView

XmlDocument oXmlDoc=new XmlDocument();

     oXmlDoc.Load("ClientConfig.xml");

     XmlNode root =oXmlDoc.DocumentElement;//获取文档根

     //XmlNode rootClient= root.SelectSingleNode("Clients");                                  IEnumerator ienum=root.GetEnumerator();

     XmlNode node;

     while(ienum.MoveNext())

     {node=(XmlNode)ienum.Current;

     this.treeView1.Nodes.Add(node.InnerText);

     }

     而选定一个TreeView的节点,重写AfterSelect事件

     获取该节点的文本this.treeView1.SelectedNode.Text.Trim();

7ArrayList数组,Queue对列

          单线程中的遍历:

IEnumerator iEnumView=m_alViews.GetEnumerator();

     while(iEnumView.MoveNext())

{

     View view=(View)IEnumView.Current;

};

在多线程中,如果ArrayList被同步使用,都按上面的遍历方法,如果链表中元素变化,会出现异常叫安全的做法遍历是创建副本,遍历副本

     ArrayList Temp=m_alViews.Clone();

IEnumerator iEnumView=m_ Temp.GetEnumerator();

     while(iEnumView.MoveNext())

{

     View view=(View)IEnumView.Current;

};

     更新链表,遍历取出的view仅仅是链表的枚举元素,而不是链表的节点.通常更新的做法是.

取出待更新的节点的序号.

//大部分时候必须通过遍历来找序号

int nIndex=0;

IEnumerator iEnumView=m_alViews.GetEnumerator();

while(iEnumView.MoveNext())

{

If(view.a==((View)IEnumView.Current).a)//a是指表示一个节点的重要元素

Break;  

nIndex++;

};

//小部分直接取

int nIndex=m_alView.Indexof(object);

//object的更新过程

     ……

m_alViews[nIndex]=object;

 

Queue对列,先进先出的链表

添加元素

MyQueue.Enqueue(nTest.ToString());

查看并删除最先进入的元素

object temp=MyQueue.Dequeue()

查看最先进入的元素

object temp=MyQueue.Peek()

查看最新的元素。

Object [] objectlist=MyQueue.ToArray();

Object objecttemp=objectlist[MyQueue.Count-1];

遍历QueueArrayList相似。

IEnumerator iEnum=mMyQueue.GetEnumerator();

8String的初始化以及String与其他类型数据的转化

     String str=String.Format(“This is a test {0},{1}”,strA,strB);

     几乎所有的Object包括值类型都有ToString()方法。

     String str=intA/boolA/……ToString();

    Ushort a=Convert.ToUInt16(0x0011,16);

     Byte型的Tostring 将返回ASCII,而不是字符本身.

     Byte.ToString(“c/d……”)

格式字符

说明

“C”“c”

货币格式。

“D”“d”

十进制格式。

“E”“e”

指数表示法格式。

“F”“f4”

固定点格式。(小数点后4位)

“G”“g”

常规格式。

“N”“n”

数字格式。

“P”“p”

百分比格式。

“X”“x”

十六进制格式。

 

     String转为相应的其他基本类型。

     Convert.ToInt32/ToBoolean/......(Str);

9TabControl使用

     属性-TabPages-add

10ToolBar使用

     添加按钮:a、添加一个ImageList

               b、属性-Buttons-Add(设置ImageIndex

     添加Click事件:

Private void toolBar_ButtonClick(objectsender, System.Windows.Forms.ToolBarButtonClickEventArgs  e)

         {Switch(e.Button.ImageIndex){……}}

11DataGrid使用

ADataAdapter

a、绑定数据

DataTable dt=new DataTable();

          SqlDataAdapter datadapter=new SqlDataAdapter(strSql,Connection);

         //必须的,这样才能更新数据

         SqlCommandbuilder Cb=new SqlCommandbuilder(datadapter);

          datadapter.Fill(dt);//填充SqlDataAdapter

this.DataGrid.DataSource = dt;//绑定DataTableDataGrid

b、通过DataGrid更新数据(和上面的程序对应)

DataTable changes = dt.GetChanges();//获取更改

         datadapter.Update( changes );//更新数据库数据(前提表与SQL完全对应,包含所有列

dt.AcceptChanges();//DataTable接受更改

     BDataSetXML

         a、绑定数据

System.Data.DataSet objDataSet=new DataSet();

         objDataSet.ReadXml("book.xml");

         dataGrid1.DataSource=m_objDataSet;//绑定

         dataGrid1.DataMember="book";//显示其中的一个DataTable

         b、更改DataGrid中的数据通过DataSet更新数据

         objDataSet.AcceptChanges();

         objDataSet.WriteXml("book.xml");

     C、设置头文字

DataGridView1.Columns[0].HeaderText = "编号";

     D、设置为自动扩展

DataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);

     E、最后一列为Fill等属性。

dataGridView1.Columns[4].AutoSizeMode=DataGridViewAutoSizeColumnMode .Fil

     F、设置选择方式

         设置SelectMode属性:行选、列选、cell选。

     G、怎样往Grid中添加string[,] 列表

         private void DataBind( DataGridView ViewTemp,

 string[,] strList, int nColumns, int nRows)

        {for (int nIndex = 0; nIndex < nRows; nIndex++)

            {int nCount = this.dataGridView1.Rows.Count;

                this.dataGridView1.Rows.Insert(nCount - 1);

                for (int m = 0; m < nColumns; m++)

                { this.dataGridView1.Rows[nCount - 1].Cells[m].Value =

strList[nIndex, m]; } } }

12、正则表达式语法

字符匹配语法:

字符语法

语法解释

语法例子

/d

匹配数字(0~9

‘/d’匹配8,不匹配12

/D

匹配非数字

‘/D’匹配c,不匹配3

/w

匹配任意单字符

‘/w/w’ 匹配A3,不匹配@3

/W

匹配非单字符

‘/W’匹配@,不匹配c

/s

匹配空白字符

‘/d/s/d’匹配3 d,不匹配abc

/S

匹配非空字符

‘/S/S/S’匹配A#4,不匹配3 d

.

匹配任意字符

‘....’匹配A$ 5,不匹配换行

[…]

匹配括号中任意字符

[b-d]匹配bcd, 不匹配e

[^…]

不匹配括号内字符

[^b-z]匹配a,不匹配b-z的字符;

   重复匹配语法:

重复语法

语法解释

语法例子

{n}

匹配n次字符

/d{3}匹配/d/d/d,不匹配/d/d/d/d/d/d

{n,}

匹配n次和n次以上

/w{2}匹配/w/w/w/w/w以上,不匹配/w

{n,m}

匹配n次上m次下

/s{1,3}匹配/s,/s/s,/s/s/s,不匹配/s/s/s/s

?

匹配01

5?匹配50,不匹配非50

+

匹配一次或多次

/S+匹配一个以上/S,不匹配非一个以上/S

*

匹配0次以上

/W*匹配0以上/W,不匹配非N*/W

    字符定位语法:

重复语法

语法解释

语法例子

^

定位后面模式开始位置

 

$

前面模式位于字符串末端

 

/A

前面模式开始位置

 

/z

前面模式结束位置

 

/Z

前面模式结束位置(换行前)

 

/b

匹配一个单词边界

 

/B

匹配一个非单词边界

 

    转义匹配语法:

转义语法

涉及字符(语法解释)

语法例子

“/”+实际字符

/ . * + ? | ( ) { }^ $

例如://匹配字符“/”

/n

匹配换行

 

/r

匹配回车

 

/t

匹配水平制表符

 

/v

匹配垂直制表符

 

/f

匹配换页

 

/nnn

匹配一个8进制ASCII

 

/xnn

匹配一个16进制ASCII

 

/unnnn

匹配416进制的Uniode 

 

/c+大写字母

匹配Ctrl-大写字母

例如:/cS匹配Ctrl+S

  构造正则表达式需要涉及Regex类,在Regex类中包括:IsMatch()Replace()Split()Match的类;

如果使用的是 C#,则可以使用以 @ 为前缀以禁用转义的 C# 字符串(例如 @"/s2000",/s不再转义。

13、定时器组件(Timer

     timer.Interval=1000;//设置Tick事件的产生间隔,单位:ms

     Tick事件中进行事务的处理

     Timer.Enabled=True;//启动定时器,=false关闭定时器。

     Timer.Start();    

定时器的疑问:为什么只要=false,或者Stop后定时器不能再次的使用。

14ListBox显示最后一行或者倒序显示

     this.listBox1.Items.Add(nTest);

     //this.listBox1.Items.Insert(0,nTest);// 倒序显示

     this.listBox1.SelectedIndex=(this.listBox1.Items.Count)-1;//显示最后一行

15Equals==

         对于几乎所有引用类型,当您希望测试相等性(每一项均等)而不是引用一致性时,请使用 Equals,当要判断是否引用了同一对象时使用“==”。

对于值类型和字符串,我通常使用 ==,因为除非值类型本身包含引用类型(这种情况极为罕见)。

16Close窗口前的询问。

     private void Form_Closing(object sender, System.ComponentModel.CancelEventArgs e)

{DialogResult dr = System.Windows.Forms.MessageBox.Show(this,"如果您想退出系统,请单击“确定”按钮,否则单击“取消”按钮?","退出系统",System.Windows.Forms.MessageBoxButtons.OKCancel);

              if(dr != DialogResult.Cancel)

              {

                   this.readerThread.interrupt();

                   try

                   {trapReceiverInterface.stopReceiving();}

                   catch(System.Exception ex)

                   {System.Console.Write(ex.Message);}

              }

              else{e.Cancel = true;//窗口不关闭}

         }

17、线程

Thread.Sleep(int i):将当前线程阻塞(暂停)指定的毫秒数,并使线程处于WaitSleepJoin状态。可以通过Thread.Interrupt()来唤醒它。
Thread.Suspend()
:挂起(睡眠)线程,或者如果线程已挂起,则不起作用。如果不使用Thread.Resume()来唤醒它,则线程被永久的挂起。
Thread.Join():
阻塞(暂停)调用线程,直到某个线程终止时为止。常和Thread.Abort一起使用,保证线程被顺利结束。
Thread.Abort():
终止当前线程的执行,在线程上调用此方法时,系统在此线程中引发 ThreadAbortException 以中止它。

System.Threading.Thread hRcvThread=new Thread(new System.Threading.ThreadStart (RcvThreadFunc));

     hRcvThread.Start();

     private void RcvThreadFunc(){while(hRcvThread.Isalive){}};

     停止线程:

     if(hRcvThread!=null)

     {hRcvThread.Abort();

     //加上一个比较长的时间片,在.net 2.0

     hRcvThread.Join(20000);}

18、位操作 ^ &

     ^操作赋:当且仅当一个为1时结果为1.

     &当且仅当两个都为1时结果为1.

         byte bytea=0xEA;

         int inta=bytea & 0xF0;//=0xE0

         int intb=bytea ^ 0xF0;//=0x11

19、多维数组初始化

a、可以在声明数组时将其初始化,如下例所示:

int[,] myArray = new  int[,] {{1,2}, {3,4}, {5,6}, {7,8}};

int [] myArray=new int[5,6];

b、也可以初始化数组但不指定级别:

  int[,] myArray = {{1,2}, {3,4}, {5,6}, {7,8}};

c、如果要声明一个数组变量但不将其初始化,必须使用 new 运算符将数组分配给此变量。例如:

int[,] myArray;

myArray = new int[,] {{1,2}, {3,4}, {5,6}, {7,8}};   // OK

myArray = {{1,2}, {3,4}, {5,6}, {7,8}};   // Error

d、也可以给数组元素赋值,例如:

  myArray[2,1] = 25;

20、线程同步

     private ManualResetEvent EventReader,EventDisposer;

     EventReader=new ManualResetEvent(true);

互斥两个线程使用两个ManualResetEvent

EventReader.WaitOne();

     EventDisposer.Reset();

EventDisposer.Set();

21C#加载一般C++DLL

using System.Runtime.InteropServices;

[DllImport("cfsend.dll",EntryPoint="RCReadCard",CharSet=CharSet.Ansi,CallingConvention=CallingConvention.StdCall)]

     unsafe public static extern int CNXReadCard(byte * sbuff, uint dItemSize,int nDev);

     如果使用了指针,在前面加上unsafe标示。注意unsafefixed关键字都有一个{}表示的作用范围.

     unsafe {     Buff=new byte[188*204*2];

              while(hRcvThread.IsAlive)

{fixed(byte * pTemp=Buff)

{                                                            nRcvData=CNXReadCard(pTemp,188*204*2,nDevHandle);

                   m_objDataDispose.ReceiveData(Buff,nRcvData);

                   }

                   }

              }

22UserControl使用

     private baseinfocontrol baseinfoc;

     baseinfoc=new baseinfocontrol();

baseinfoc.Hide();//隐藏。

     this.panelClient.Controls.Add(baseinfoc);

     baseinfoc.Show();//显示。

     定位:baseinfoc.Location=new Point(100,100);

          或者 this.panelClient.Controls[0].Location=new Point(100,100);

     如果想使用UserControl的事件,最好是将所有UserControl的内部控件的该事件一起定向为

     UserControl的该事件函数,例如:MouseDoubleClick,应当将控件以及其所包含的所有控件的

     MouseDoubleClick事件定义为同一个事件函数,UserControl_MouseDoubleClick.

23ADO.Net简介

     MySQLClient(OracleClient与它相似)

a)   SqlDataAdapter 不会自动生成实现 DataSet 的更改。但是,如果设置了 SqlDataAdapter SelectCommand 属性,则可以创建一个 SqlCommandBuilder 对象来自动生成用于单表更新的 Transact-SQL 语句。

b)   如果在检索元数据后(例如在第一次更新后)更改 SelectCommand,则应调用 SqlCommandBuilder.RefreshSchema 方法来更新元数据;

public static DataSet SelectSqlSrvRows(string myConnection, string mySelectQuery, string myTableName)

{

   SqlConnection myConn = new SqlConnection(myConnection);

   SqlDataAdapter myDataAdapter = new SqlDataAdapter();

//使适配器与SQL语句结合

   myDataAdapter.SelectCommand = new SqlCommand(mySelectQuery, myConn);

//适配器与Builder结合

   SqlCommandBuilder cb = new SqlCommandBuilder(myDataAdapter);

   myConn.Open();

   DataSet ds = new DataSet();

   //填充DataSet使得DataSet可与DataGrid等控件结合使用

   myDataAdapter.Fill(ds, myTableName);

   //改变DataSet的代码

   //如果没有 SqlCommandBuilder 下面的代码将失败。

   myDataAdapter.Update(ds, myTableName);

   myConn.Close();

   return ds;

}

c)   SqlCommandSqlDataReader

可以重置 CommandText 属性并重用 SqlCommand 对象。但是,在执行新的命令或先前命令之前,必须关闭 SqlDataReader

public void ReadMyData(string myConnString)

{

   string mySelectQuery = "SELECT OrderID, Customer FROM Orders";

   SqlConnection myConnection = new SqlConnection(myConnString);

   SqlCommand myCommand = new SqlCommand(mySelectQuery,myConnection);

   myConnection.Open();

//必须调用CommandExcute(ExecuteReader, ExecuteNonQuery)方法来初始化Reader

   SqlDataReader myReader = myCommand.ExecuteReader();

   try

   {while (myReader.Read())

     { Console.WriteLine(myReader.GetInt32(0) + ", " + myReader.GetString(1));

     }

    }

    finally

    {

    // always call Close when done reading.

    myReader.Close();

    myConnection.Close();

    }

 }

24using的使用

     a)用于引用命名空间。

         using System;

     b)用于定义别名并使用该命名空间。

         using MyAlias = MyCompany.Proj.Nested;

d)   using 语句定义一个范围,在此范围的末尾将处理对象。

    using (Font MyFont = new Font("Arial", 10.0f), MyFont2 = new Font("Arial", 10.0f))

      {// use MyFont and MyFont2

      }// compiler will call Dispose on MyFont and MyFont2

25、一步一步实现COM+COM+服务设置。

      1)创建一个C# 类库工程。

      2)在引用中添加System.EnterpriseServices

      3using System.EnterpriseServices;

      4给程序添加强名(strong name//COM+组件必须的。

         a)开始-〉程序-Microsoft Visual Studio .NET 2003-Visual Studio .NET 工具

                -Visual Studio .NET 2003 命令提示

         b)在命令提示下sn.exe –k Mykey.snk //名字随便。扩展名一般用snk

         c)签名:打开工程中的AssemblyInfo.cs文件并进行修改。

         [assembly:AssemblyKeyFile(“..//..// Mykey.snk”)] //表示snk文件位置。   

5)添加业务逻辑。   

//表明需要事务支持

     [ Transaction(TransactionOption.Required) ]

     //表明该类为组件类,必须有至少一个类继承于ServicedComponent

     public class DBManager : ServicedComponent

     {……

}

        6)编译程序。

        7)在命令提示符下输入:

              注册 :regsvcs 文件路径/文件名.dll

注销 :regsvcs /u 文件路径/文件名.dll//两种斜杠。

        这样DLL就会被注册到COM+ Service中。

26、启动时最大化窗口

     MainForm objMainForm=new MainForm();

    objMainForm.WindowState = FormWindowState.Maximized;

Application.Run(objMainForm);

27Check型的子菜单使用。

     //菜单click事件

private void tabPageToolStripMenuItem_Click(object sender, EventArgs e)

{    System.Windows.Forms.ToolStripMenuItem ObjectTemp = (System.Windows.Forms.ToolStripMenuItem)sender;

//如果当前的状态为没选中,那么click后则为选中

            if (ObjectTemp.CheckState==CheckState.Unchecked{ this.panel1.Show();

                ObjectTemp.CheckState = CheckState.Checked;}

            else{this.panel1.Hide();

                ObjectTemp.CheckState = CheckState.Unchecked;}

}

28、布局管理

     Control.Dock=DockStyle.Fill/Bottom/Top/Left/Right/None

右键点击控件,弹出的菜单”bring to front”,”bring to back”,可以调节控件的相容性.

29、启动其他进程

     System.Diagnostics .Process myProcess = new Process();

//知道本进程的路径,包含运行的文件名

     string myAppPath = Application.ExecutablePath;

     //找到最后一个//以便除去本进程的运行的文件名

    int nIndex =myAppPath.LastIndexOf("//");

     //除去文件名

     myAppPath = myAppPath.Substring(0, nIndex);

/*直接使用string myAppPath =Application.StartupPath可以直接取得*/

     //加上待运行的文件名称

myProcess.StartInfo.FileName = myAppPath + "//SNMPManager.exe";

myProcess.Start();

30、获取本地IP

System.Net.IPAddress[] addressList =Dns.GetHostEntry(Dns.GetHostName()).AddressList;

String strIp=addressList[0].ToString();

31、获取程序运行路径、运行其他的应用程序

     //获取应用程序运行路径

     string myAppPath = Application.ExecutablePath;

     int nIndex =myAppPath.LastIndexOf("//");

     myAppPath = myAppPath.Substring(0, nIndex);

     //设置另外的应用程序的路径,并运行。

myProcess.StartInfo.FileName = myAppPath + "//SNMPManager.exe";

myProcess.Sart();

32OpenFileDialog的使用

//设置初始目录

openFileDialog.InitialDirectory = strPath;

//设定可选择的文件类型

openFileDialog.Filter = "图标|*.ico|Bitmap图像|*.bmp|JPEG图像|*.jpg";

//默认的文件类型

openFileDialog.FilterIndex = 1;

openFileDialog.RestoreDirectory = false;

     //第一个或者最后一个文件的名称

openFileDialog.FileName = "";

if (this.openFileDialog.ShowDialog() == DialogResult.OK)

33XML文档读写

     A、读取XML的一个子节点的属性

     XmlDocument oXmlDoc=new XmlDocument();

//!!!注意啦,使用Load而不是LoadXml

     oXmlDoc.Load("Config.xml");

     XmlNode root =oXmlDoc.DocumentElement;//获取文档根

//获取名为OIDInfoList的父节点。

     XmlNode rootStructInfo= root.SelectSingleNode("OIDInfoList");

     IEnumerator ienum=rootStructInfo.GetEnumerator();

     XmlAttributeCollection oXmlAttributeCollection;

     XmlAttribute attr;

//遍历OIDInfoList父节点的所有字节点。

     while(ienum.MoveNext())

     {

          XmlNode nodeOIDInfo;

structOIDInfo otempOIDInfo;

//将子节点赋值给nodeOIDInfo

 nodeOIDInfo=(XmlNode)ienum.Current;

//获取nodeOIDInfo的属性集

         oXmlAttributeCollection=nodeOIDInfo.Attributes;

         //获取指定OID的一个属性。

         attr=(XmlAttribute)oXmlAttributeCollection.GetNamedItem("OID");

         otempOIDInfo.strOID=attr.Value;

//改变属性值

rootStructInfo.ChildNodes[nIndex].Attributes[1].Value = strImagePath  }

//添加新的子节点, XmlNode为抽象积基类,不能实例化

XmlNode XmlNodeChild = rootStructInfo.ChildNodes[0].Clone();

         XmlNodeChild.Attributes[0].Value=strType;

         XmlNodeChild.Attributes[1].Value=strImagePath;

NodeTypePath.AppendChild(XmlNodeChild);

}

//保存到文件

oXmlDoc.Save("Config.xml");

     添加节点

XmlDocument Doc = new XmlDocument();

            Doc.Load(Application.StartupPath+"//Log//AnalogSignalMonitorAlarm.xml");

        XmlElement Noderoot = Doc.DocumentElement;

       XmlNode NodeList = Noderoot.SelectSingleNode("AlarmLogList");

            XmlElement ElementAdd = Doc.CreateElement("AlarmLog");

            ElementAdd.SetAttribute("ChanelID", nChannelID.ToString());

ElementAdd.SetAttribute("PGName", strPGName);

       ElementAdd.SetAttribute("DateTime", strDateTime);

            ElementAdd.InnerText = strMsg;

        NodeList.AppendChild(ElementAdd);

        Doc.Save(Application.StartupPath"//Log//AnalogSignalMonitorAlarm.xml");

 

     XML格式

     <?xml version="1.0" encoding="utf-8" ?>

<Config>

          <OIDInfoList>

              <OIDInfo OID="1.3.6.2.1.1.1" Value="Windows" RW="true" ></OIDInfo>

              <OIDInfo OID="1.3.6.1.2.1.1.2.0" Value="1.11" RW="false" ></OIDInfo>

              <OIDInfo OID="1.3.6.1.2.1.1.3.0" Value="2-11" RW="true" ></OIDInfo>

              <OIDInfo OID="1.3.6.1.2.1.1.4.0" Value="演示" RW="false" ></OIDInfo>

              <OIDInfo OID="1.3.6.1.2.1.1.5.0" Value="管理员" RW="false" ></OIDInfo>

              <OIDInfo OID="1.3.6.1.2.1.1.6.0" Value="655" RW="true" ></OIDInfo>

              <OIDInfo OID="1.3.6.1.2.1.1.7.0" Value="123" RW="true" ></OIDInfo>

          </OIDInfoList>    

          <IP>192.168.127.192</IP>

</Config>

34Panel的使用

     a、将控件加入Panel

         PanelClient.Controls.Add(userControl);

     b、将控件带入到可视范围

         panelClient.ScrollControlIntoView(NodeTemp);

35OKCancel按钮,不退出对话框

     If{ MessageBox.Show("密码输入不一致!");

                DialogResult = DialogResult.None; }

36TreeView补遗

     在添加TreeView时添加Key

     TreeView.Nodes.Add(string strKey,string strText);

     这样查找的时候(一级)

     int nIndex=TreeView.Nodes.IndexOfKey(strkey);

     注意点这样以来就不能使用TreeNode的方式往TreeView中添加子节点了

     只能通过TreeView.Nodes.Add的方式, IndexOfKey只能查找本级Nodes,如果Nodes有多级的

     :  (两级示例,多级同理).

         TreeNode [] Temp= this.treeViewDevice.Nodes.Find(strOldIP,true);

          int nIndexParent = this.treeViewDevice.Nodes.IndexOf(Temp[0].Parent);

     int nIndex = treeViewDevice.Nodes[nIndexParent].Nodes.IndexOfKey(strOldIP);

可以将一个对象与一个Node结合一起

     //绑定

          TreeNode TreeNodeTemp2 = new TreeNode(MIbInfoTemp.strOID);

     TreeNodeTemp2.Tag = MIbInfoTemp;

treeViewMIB.Nodes.Add(TreeNodeTemp2);

//取出

         MIBInfo MIBInfotemp = (MIBInfo)treeViewMIB.SelectedNode.Tag;

     textBoxObjectName.Text = MIBInfotemp.strObjectName;

37、显示TableControl下的某一tabletage

     this.tablecontrol1.SelectedIndex=0,1,2,……;

38、设置焦点

     This.panel.Focus();

39、比较大小Math.Max(i,j)

    Int x =System.Math.Max(I,J);Max方法有20中的重构,用于不同的类型.

40、窗体大小不可变

     this.FormBorderStyle=FormBorderStyle.FixedSingle;当然也可以在窗体属性中设置。

41、链表范型

    System.Collections.Generic.List<Type A>  List=new List<Type A>;

 

1String链表类

DotNet为字符串创建了链表命名空间System.Collections.Specialized,以及类stringcollection

2、委托的使用

3、进度条的使用

progressBar1.Value = 30;//表示进度为30%

4radioButton

    重要的属性:Checked

    重要的事件:CheckedChangedClick

5、换行

    /r/n回车换行符。

6、怎样使DataGridView与零散数据结合

     table.Columns.Add("str1", typeof(String));

     table.Columns.Add("str2", typeof(String));

     table.Columns.Add("str3", typeof(String));

     table.Rows.Add("1","1","1");

     table.Rows.Add("1", "1", "1");

     table.Rows.Add("1", "1", "1");

     dataGridView1.DataSource = table;

     //调准列的现实位置

dataGridView1.Columns[0].DisplayIndex = 3;

 

7、串口程序

    using System.IO.Ports;

private SerialPort Port;

private void Form1_Load(object sender, EventArgs e)

   {

       //初始化串口

        Port = new SerialPort("COM1", 9600, Parity.None, 8, StopBits.One);

//通过事件回调,当数据产生时,事件触发。

Port.DataReceived += new SerialDataReceivedEventHandler(Port_DataReceived);

       Port.ReadBufferSize =10;

      //打开串口

       Port.Open();

     }

private void Port_DataReceived(object sender, SerialDataReceivedEventArgs e)

{

     string strDatateime = Port.ReadExisting();

   }

8、注册表读写

    Int32 registData;

     RegistryKey hkml = Registry.LocalMachine;

    //注意第二个参数true表示可写,false表示只读.

     RegistryKey kSystem = hkml.OpenSubKey ("SYSTEM//CurrentControlSet//Services//W32Time//TimeProviders//NtpClient", true);

     //获取NtpClient的一个属性值SpecialPollInterval

registData = (Int32)kSystem.GetValue("SpecialPollInterval");

//赋值

kSystem.SetValue("SpecialPollInterval ", “fff”);

9SQL Server 2005 Express版连接字符串

10、获取机器信息

Environment.MachineName 属性

Environment.UserDomainName 属性

Environment.UserName 属性

Environment.WorkingSet 属性

11、创建一种新的ColorBrush

public void MainForm_Paint(object sender, System.Windows.Forms. PaintEventArgs e)

{

Bitmap objBitmap;
Graphics objGraphics=
e.Graphics;
Brush objBrush;
Brush objBrush2;
// Create Bitmap
objBitmap = new Bitmap( 400, 400 );
objGraphics = Graphics.FromImage( objBitmap );
// Create Different Colored Brushes
objBrush = new SolidBrush( Color.Blue );
objBrush2 = new SolidBrush( Color.FromArgb( 100, Color.Orange ) );
// Create Rectangles
objGraphics.FillRectangle( objBrush, 10, 10, 100, 100 );
objGraphics.FillRectangle( objBrush2, 50, 50, 100, 100 );

}

12、使系统发出蜂鸣声、报警声等

    using System.Media;

    //仅仅发一次声音

    SystemSounds.Beep.play();(Beep/Exclamation/Question/Head);

14、如何在Winform中全屏显示
  this.FormBorderStyle=  System.Windows.Forms.FormBorderStyle.None;  
  this.WindowState= System.Windows.Forms.FormWindowState.Maximized;  
  this.TopMost =true;  

15、播放wav文件

    System.Media.SoundPlayer SoundPlayerObj= new SoundPlayer();

    SoundPlayerObj.Stream = My.Resources.PHONE9

SoundPlayerObj.SoundLocation = "C://a.wav";
SoundPlayerObj.Play()

16ToString()的使用

12345.ToString("n"); //生成 12,345.00 
12345.ToString("C"); //
生成 12,345.00 
12345.ToString("e"); //
生成 1.234500e+004 
12345.ToString("f4"); //
生成 12345.0000 
12345.ToString("x"); //
生成 3039 (16进制
12345.ToString("p"); //
生成 1,234,500.00% 

17、获取驱动器、文件夹、文件信息

    命名空间:System.IO

    类:File,Directory,DriverInfo  

18DateTimeToString方法和所得字符串结果

   

   注意:ToString("yyyy/MM/dd hh:mm:ss")得到的是12小时制的时间如果要得到24小时制的使用

strParse = "2006-09-01 11:12:08";

          timeTemp = DateTime.Parse(strParse);

strDatetime = timeTemp.ToString("yyyy-MM-dd ") + timeTemp.ToLongTimeString();

          if (timeTemp.Hour < 10)

          {

             strDatetime = strDatetime.Insert(11, "0");

          }

          Assert.AreEqual(strParse, strDatetime);

19、特别要注意的地方,出错但是debug不会弹出错误

ErrorInfo Temp = (ErrorInfo)(ErrorLog.ListError.Dequeue());

如果这时ErrorLog.ListError.Count等于0那么会出现错误,但是没有任何的debug信息,程序直接退出,相当的恐怖。

20、使用属性将ArrayListdatagridview相结合以显示数据。

    ArrayList List = new ArrayList();

    teststruct test = new teststruct();

    test.stra3 = "xtj";

    test.性别= "";

    test.问候语= "你好";

    for (int m = 0; m < 1000;m++ )

        List.Add(test);

dataGridView1.DataSource = List;

//调准位置

    dataGridView1.Columns[0].DisplayIndex = 3;

public struct teststruct

    {

       

        private string stra2;

        public string 性别

        {

            get { return stra2; }

            set { stra2 = value; }

        }

        private string stra1;

        public string 问候语

        {

            get { return stra1; }

            set { stra1 = value; }

        }

        public string stra3;

        public string 姓名

        {

            get { return stra3; }

            set { stra3 = value; }

        }

    }

21、渐变色的使用

using System.Drawing.Drawing2D;

   private void UserControlBaseInfo_Paint(object sender, PaintEventArgs e){

            Graphics graphicsobj = e.Graphics;

            Rectangle rec=new Rectangle(0, 0, this.Width, this.Height);

            graphicsobj.FillRectangle(new LinearGradientBrush(rec, Color.Blue, Color.White, LinearGradientMode.Vertical), rec);

        }