C#學習總結(一)

來源:互聯網
上載者:User

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、Regex簡單應用(匹配,替換,拆分)

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");

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.