zoukankan      html  css  js  c++  java
  • C#学习总结(一)

    http://blog.sina.com.cn/s/blog_40e97d530100c7g6.html

    1、 支持行选的代码。

    DataGridView1.SelectionMode =System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect;

    DataGridView1.MultiSelect=false;

    2、 控制列显示的位数

    GridView中选定某列>编辑列>选择要设置的列>将此字段转换为模板>确定>编辑模板>选择 label>编辑>自定义绑定中>eval_r("au_fname").ToString().Substring(0,3)>确定完成.

    注意一点:Substring(0,3)不可超出字段中最少文字的字数,否则将引发索引和长度必须引用该字符串内的位置的错误!

    3、 BackgroundWorker

    当用户执行一个非常耗时的操作时,如果不借助Thread编程,用户就会感觉界面反映很迟钝。在.Net 2.0中可以通过BackgroundWork非常方便地进行Thread编程,大致的步骤是:

    1、调用BackgroundWorker的RunWorkerAsync方法(可以传递参数),它将调用DoWork事件

    2、在DoWork的事件响应代码中调用耗时的操作,此例中是PingIPs函数

    3、在耗时操作中判断CancellationPending属性,如果为false则退出

    4、如果要向用户界面发送信息,则调用BackgroundWorker的ReportProgress方法,它将调用ProgressChanged事件(可以将改变通过object类型传递)

    5、在ProgressChanged事件的响应代码中将改变呈现给用户

    6、如果需要取消耗时操作,则调用BackgroundWorker的CancelAsync方法,需要和步骤3一起使用

    4、 MDI窗体

    设有两个窗体frmMain,frmChild,则:

    frmMain: 设IsMdiContainer属性为true

    打开子窗口:

    在相关事件中写如下代码:

    frmChild child=new frmChild();

    child.MdiParent=this;//this表示本窗体为其父窗体

    child.Show();

    在打开子窗体时,如果只允许有一个子窗体,可以加入如下判断:

    if (this.ActiveMdiChild!=null)

    {

    this.ActiveMdiChild.Close(); //关闭已经打开的子窗体

    //....

    }

    更改MDI主窗体背景

    先声明一个窗体对象

    private System.Windows.Forms.MdiClient m_MdiClient;

    在Form_Load等事件中,添加如下代码:

    int iCnt=this.Controls.Count;

    for(int i=0;i<iCnt;i++)

    {

    if(this.Controls[i].GetType().ToString()=="System.Windows.Forms.MdiClient")

    {

    this.m_MdiClient=(System.Windows.Forms.MdiClient)this.Controls[i];

    break;

    }

    }

    this.m_MdiClient.BackColor=System.Drawing.Color.Silver;

    具体可参见:http://cnblogs.com/Daview/archive/2004/05/06/8381.ASPx

    5、 创建系统托盘菜单

    1,创建一个contextMenu(cmnMain)菜单

    2,添加一个NotifyIcon组件,设置ContextMenu属性为cmnMain

    3,相应窗体改变事件(最小化等)

    private void frmMain_SizeChanged(object sender,EventArgs e)

    {

    if (this.WindowState==FormWindowstate.Minimized)

    {

    this.Hide();

    noiMain.Visible=true;

    }

    }

    4,相应用户单击系统托盘上contextmenu菜单事件

    private void mniOpen(object sender,EventArgs e)

    {

    noiMain.Visible=false;

    this.Show();

    this.Focus();

    }

    5,响应用户双击系统托盘图标事件

    private void noiMain_DoubleClick(object s,EventArgs e)

    {

    minOpen.PerformClick(); //相当与mniOpen按钮的单击事件

    }

    **注意添加相应的事件句柄**

    6、 创建不规则窗体

    1,在窗体上创建不规则图象,可以用gdi+绘制,或在图象控件上使用图象填充

    2,设置窗体的backcolor为colorA,然后设置TransparencyKey为colorA

    3,设置FormBorderStyle为none;

    7、 创建顶部窗体

    this.TopMost=true;//把窗体的TopMost设置为true

    8、 调用外部程序

    using System.Diagnostics

    Process proc=new Process();

    proc.StartInfo.FileName=@"notepad.exe"; //注意路径

    proc.StartInfo.Arguments="";

    proc.Start();

    //获得当前目录Directory.GetCurrentDirectory() (using System.IO)

    9、 Toolbar的使用

    Toolbar控件通常需要imagelist控件结合使用(需要用到其中图标)

    响应Toolbar单击事件处理程序代码:

    switch(ToolbarName.Buttons.IndexOf(e.Button))

    {

    case 0: //第一个按钮

    //code ...

    break;

    case 1: //第二个按钮

    //code ...

    break;

    //other case code

    default: //默认处理,但以上所有项都不符合时

    //code ...

    break;

    }

    10弹出对话框获得相关返回值

    在窗体的closing事件中运行如下代码,可以在用户关闭窗体时询问

    DialogResult result=MessageBox.Show(this,"真的要关闭该窗口吗?","关闭提示",MessageBoxButtons.OKCancel,MessageBoxIcon.Question);

    if (result==DialogResult.OK)

    {

    //关闭窗口

    e.Cancel=false;

    }

    else

    {

    //取消关闭

    e.Cancel=true;

    }

    11、打印控件

    最少需要两个控件

    PrintDocument

    PrintPreviewDialog:预览对话框,需要printdocument配合使用,即设置document属性为

    对应的printDocument

    printdocument的printpage事件(打印或预览事件处理程序)代码,必须.

    float fltHeight=0;

    float fltLinePerPage=0;

    long lngTopMargin=e.MarginBounds.Top;

    int intCount=0;

    string strLine;

    //计算每页可容纳的行数,以决定何时换页

    fltLinePerPage=e.MarginBounds.Height/txtPrintText.Font.GetHeight(e.Graphics);

    while(((strLine=StreamToPrint.ReadLine()) != null) && (intCount<fltLinePerPage))

    {

    intCount+=1;

    fltHeight=lngTopMargin+(intCount*txtPrintText.Font.GetHeight(e.Graphics));

    e.Graphics.DrawString(strLine,txtPrintText.Font,Brushes.Green,e.MarginBounds.Left,fltHeight,new StringFormat());

    }

    //决定是否要换页

    if (strLine!=null)

    {

    e.HasMorePages=true;

    }

    else

    {

    e.HasMorePages=false;

    }

    以上代码的StreamToPrint需要声明为窗体级变量:

    private System.IO.StringReader StreamToPrint;

    打开预览对话框代码(不要写在printpage事件中)

    StreamToPrint=new System.IO.StringReader(txtPrintText.Text);

    PrintPreviewDialogName.ShowDialog();

    12string对象本质与StringBuilder,字符串使用

    string对象是不可改变的类型,当我们对一个string对象修改后将会产生一个新的string对

    象,因此在需要经常更改的字符对象时,建议使用StringBuilder类:

    [范例代码]构造一个查询字符串

    StringBuilder sb=new StringBuilder("");

    sb.Append("Select * from Employees where ");

    sb.Append("id={0} and ");

    sb.Append("title='{1}'");

    String cmd=sb.ToString();

    sb=null; //在不再需要时清空它

    cmd=String.Format(cmd,txtId.Text,txtTile.Text); //用实际的值填充格式项

    判断字符串是否为空:

    检查一个字符串是否为空或不是一个基本的编程需要,一个有效的方法是使用string类的Length属性来取代使用null或与""比较。

    比较字符串:使用String.Equals方法来比较两个字符串

    string str1="yourtext";

    if (str1.Equals("TestSting") )

    {

    // do something

    }

    13、判断某个字符串是否在另一个字符串(数组)

    需要用到的几个方法

    string.Split(char);//按照char进行拆分,返回字符串数组

    Array.IndexOf(Array,string):返回指定string在array中的第一个匹配项的下标

    Array.LastIndexOf(Array,string):返回指定string在array中的最后一个匹配项的下标

    如果没有匹配项,则返回-1

    [示例代码]:

    string strNum="001,003,005,008";

    string[] strArray=strNum.Split(',');//按逗号拆分,拆分字符为char或char数组

    Console.WriteLine(Array.IndexOf(strArray,"004").ToString());

    11,DataGrid与表和列的映射

    从数据库读取数据绑定到DataGrid后,DataGrid的列标头通常跟数据库的字段名相同,如果

    不希望这样,那么可以使用表和列的映射技术:

    using System.Data.Common;

    string strSql="select * from Department";

    OleDbDataAdapter adapter=new OleDbDataAdapter(strSql,conn);

    DataTableMapping dtmDep=adapter.TableMappings.Add("Department","部门表");

    dtmDep.ColumnMappings.Add("Dep_Id","部门编号");

    dtmDep.ColumnMappings.Add("Dep_Name","部门名称");

    DataSet ds=new DataSet();

    adapter.Fill(ds,"Department"); //此处不能用"部门表"

    响应单击事件(datagrid的CurrentCellChanged事件)

    DataGridName.CurrentCell.ColumnNumber;//所单击列的下标,从0开始,下同

    DataGridName.CurrentCell.RowNumber;//所单击行的下标

    DataGridName[DataGridName.CurrentCell];//所单击行和列的值

    DataGridName[DataGridName.CurrentRowIndex,n].ToString();//获得单击行第n+1列的值

    14、动态添加菜单并为其添加响应事件

    添加顶级菜单:

    MainMenuName.MenuItems.Add("顶级菜单一");//每添加一个将自动排在后面

    添加次级菜单:

    MenuItem mniItemN=new MenuItem("MenuItemText")

    MenuItem mniItemN=new MenuItem("MenuItemText",new EventHandler(EventDealName))

    MainMenuName.MenuItems[n].MenuItems.Add(mniItemN);//n为要添加到的顶级菜单下标,从0开始

    创建好菜单后添加事件:

    mniItemN.Click+=new EventHandler(EventDealName);

    也可以在添加菜单的同时添加事件:

    MenuItem mniItemN=new MenuItem("MenuItemText",new EventHandler(EventDealName));

    MainMenuName.MenuItems[n].MenuItems.Add(mniItemN);

    15、正则表达式简单应用(匹配,替换,拆分)

    using System.Text.RegularExpressions;

    //匹配的例子

    string strRegexText="你的号码是:020-32234102";

    string filter=@"\d{3}-\d*";

    Regex regex=new Regex(filter);

    Match match=regex.Match(strRegexText);

    if (match.Success) //判断是否有匹配项

    {

    Console.WriteLine("匹配项的长度:"+match.Length.ToString());

    Console.WriteLine("匹配项的字符串:"+match.ToString());

    Console.WriteLine("匹配项在原字符串中的第一个字符下标:"+match.Index.ToString());

    }

    //替换的例子

    string replacedText=regex.Replace(strRegexText,"020-88888888");

    Console.WriteLine(replacedText);//输出"你的号码是:020-88888888"

    //拆分的例子

    string strSplitText="甲020-32654已020-35648丙020-365984";

    foreach(string s in regex.Split(strSplitText))

    {

    Console.WriteLine(s); //依次输出"甲乙丙"

    }

    16、多线程简单编程

    using System.Threading;

    Thread ThreadTest=new Thread(new ThreadStart(ThreadCompute));

    ThreadTest.Start();//使用另一个线程运行方法ThreadCompute

    ThreadCompute方法原型:

    private void ThreadCompute()

    {}

    17、操作注册表

    using System.Diagnostics;

    using Microsoft.Win32;

    //操作注册表

    RegistryKey RegKey=Registry.LocalMachine.OpenSubKey("Software",true);

    //添加一个子键并给他添加键值对

    RegistryKey NewKey=RegKey.CreateSubKey("regNewKey");

    NewKey.SetValue("KeyName1","KeyValue1");

    NewKey.SetValue("KeyName2","KeyValue2");

    //获取新添加的值

    MessageBox.Show(NewKey.GetValue("KeyName1").ToString());

    //删除一个键值(对)

    NewKey.DeleteValue("KeyName1");

    //删除整个子键

    RegKey.DeleteSubKey("regNewKey");

  • 相关阅读:
    Thinkphp无法加载验证码 undefined function Thinkimagettftext() 解决方案 mac系统
    fragment使用不当 导致java.lang.IllegalStateException
    怎样从GitHub项目中,下载单个文件夹或文件
    Android 5.0 app样式
    OpenCV fitline直线拟合函数学习
    Linux文件系统
    Ubuntu 12.04 笔记本触摸板失灵解决方法
    利用微软测试工具PICT生成测试用例
    Myeclipse 使用JUnit 进行单元测试
    Myeclipse 2014 安装checkstyle、PMD和Metrics
  • 原文地址:https://www.cnblogs.com/blsong/p/1805226.html
Copyright © 2011-2022 走看看