//initial DataTable dt = new DataTable(); dt.Columns.Add("ID"); dt.Columns.Add("DATE"); DataRow DR1 = dt.NewRow(); DR1["ID"] = "T01"; DR1["DATE"] = "2013-01-01"; DataRow DR2 = dt.NewRow(); DR2["ID"] = "T01"; DR2["DATE"] = "2013-01-02"; dt.Rows.Add(DR1); dt.Rows.Add(DR2); //使用ROWS.FIND dt.PrimaryKey = new DataColumn[] { dt.Columns["ID"], dt.Columns["DATE"] }; object[] findTheseVals = new object[2]; // Set the values of the keys to find. findTheseVals[0] = "T01"; findTheseVals[1] = "2013-01-01"; var foundRow = dt.Rows.Find(findTheseVals); //使用DEFAULTVIEW.FIND object[] ss=new object[2]; ss[0]="T01"; ss[1]="2013-01-02"; dt.DefaultView.Sort = "ID,DATE Asc"; int index = dt.DefaultView.Find(ss); //使用LINQ var linqRow = (from dto in dt.AsEnumerable() where dto.Field("STORAGE_ID").ToString() == "TO1" select dto).First();
2013年5月23日 星期四
【C#】DATATABLE查詢
2013年4月10日 星期三
【C#】REF與OUT
ref和out的區別在C#
中,既可以通過值也可以通過引用傳遞參數。通過引用傳遞參數允許函數成員更改參數的值,並保持該更改。若要通過引用傳遞參數,
可使用ref或out關鍵字。ref和out這兩個關鍵字都能夠提供相似的功效,其作用也很像C中的指針變量。它們的區別是:
1、使用ref型參數時,傳入的參數必須先被初始化。對out而言,必須在方法中對其完成初始化。
2、使用ref和out時,在方法的參數和執行方法時,都要加Ref或Out關鍵字。以滿足配對條件。
3、out適合用在需要retrun多個回傳值的地方,而ref則用在需要被呼叫的方法修改呼叫者丟進的參數時。
註:在C#中,方法的參數傳遞有四種類型:
(1)傳值(by value)
(2)傳址(by reference)
(3)輸出參數(by output)
(4)數組參數(by array)。
(1)傳值參數無需額外的修飾符
(2)傳址參數需要修飾符ref
傳值參數在方法調用過 程中如果改變了參數的值,那麼傳入方法的參數在方法呼叫完成以後並不因此而改變,而是保留原來傳入時的值。
傳址參數恰恰相反,如果方法調用過程改變了參數 的值,那麼傳入方法的參數在調用完成以後也隨之改變。實際上從名稱上我們可以清楚地看出兩者的含義--傳值參數傳遞的是調用參數的一份拷貝,而傳址參數傳 遞的是調用參數的內存地址,該參數在方法內外指向的是同一個存儲位置。
方法參數上的 ref 方法參數關鍵字使方法引用傳遞到方法的同一個變數。當控制傳遞呼叫方法時,在方法中對參數所做的任何更改都將反映在該變數中。
若要使用 ref 參數,必須將參數作為 ref 參數顯式傳遞到方法。ref 參數的值被傳遞到 ref 參數。
傳遞到 ref 參數的參數必須最先初始化。將此方法與 out 參數相比,後者的參數在傳遞到 out 參數之前不必顯式初始化。屬性不是變數,不能作為 ref 參數傳遞。如果兩種方法的宣告只在它們對 ref 的使用方面不同,則將出現重載。但是,無法定義僅在 ref 和 out 方面不同的重載。
out方法參數上的 out 方法參數關鍵字使方法引用傳遞到方法的同一個變數。當控制傳遞迴調用方法時,在方法中對參數所做的任何更改都將反映在該變量中。
當希望方法返回多個值時,聲明 out 方法非常有用。使用 out 參數的方法仍然可以返回一個值。一個方法可以有一個以上的 out 參數。
若要使用 out 參數,必須將參數作為 out 參數顯式傳遞到方法。out 參數的值不會傳遞到 out 參數。不必初始化作為 out 參數傳遞的變數。然而,必須在方法返回之前為 out 參數賦值。
屬性不是變量,不能作為 out 參數傳遞。
網上有很多文章說ref 只傳值,out傳地址等等這種說法,好像不是非常的準確。以下是測試碼大家可以去試試:
總結一句,ref是有進有出,而out是只出不進。
1、使用ref型參數時,傳入的參數必須先被初始化。對out而言,必須在方法中對其完成初始化。
2、使用ref和out時,在方法的參數和執行方法時,都要加Ref或Out關鍵字。以滿足配對條件。
3、out適合用在需要retrun多個回傳值的地方,而ref則用在需要被呼叫的方法修改呼叫者丟進的參數時。
註:在C#中,方法的參數傳遞有四種類型:
(1)傳值(by value)
(2)傳址(by reference)
(3)輸出參數(by output)
(4)數組參數(by array)。
(1)傳值參數無需額外的修飾符
String _Value="xx"; FunctionByValue(_Value ); { }
(2)傳址參數需要修飾符ref
String _Value="xx"; FunctionByReferance(ref _Value ); public void FunctionByReferance( ref string Value) { }(3)輸出參數需要修飾符out
String _Value="xx"; FunctionByOutput(out _Value ); public void FunctionByOutput( out string Value) { }(4)數組參數需要修飾符params(有點像是模擬MAN的方式)
UseParams(100, 'a', "keywords"); public static void UseParams(params object[] list) { for (int i = 0; i < list.Length; i++) { Response.Write(list[i]); }
傳值參數在方法調用過 程中如果改變了參數的值,那麼傳入方法的參數在方法呼叫完成以後並不因此而改變,而是保留原來傳入時的值。
傳址參數恰恰相反,如果方法調用過程改變了參數 的值,那麼傳入方法的參數在調用完成以後也隨之改變。實際上從名稱上我們可以清楚地看出兩者的含義--傳值參數傳遞的是調用參數的一份拷貝,而傳址參數傳 遞的是調用參數的內存地址,該參數在方法內外指向的是同一個存儲位置。
方法參數上的 ref 方法參數關鍵字使方法引用傳遞到方法的同一個變數。當控制傳遞呼叫方法時,在方法中對參數所做的任何更改都將反映在該變數中。
若要使用 ref 參數,必須將參數作為 ref 參數顯式傳遞到方法。ref 參數的值被傳遞到 ref 參數。
傳遞到 ref 參數的參數必須最先初始化。將此方法與 out 參數相比,後者的參數在傳遞到 out 參數之前不必顯式初始化。屬性不是變數,不能作為 ref 參數傳遞。如果兩種方法的宣告只在它們對 ref 的使用方面不同,則將出現重載。但是,無法定義僅在 ref 和 out 方面不同的重載。
out方法參數上的 out 方法參數關鍵字使方法引用傳遞到方法的同一個變數。當控制傳遞迴調用方法時,在方法中對參數所做的任何更改都將反映在該變量中。
當希望方法返回多個值時,聲明 out 方法非常有用。使用 out 參數的方法仍然可以返回一個值。一個方法可以有一個以上的 out 參數。
若要使用 out 參數,必須將參數作為 out 參數顯式傳遞到方法。out 參數的值不會傳遞到 out 參數。不必初始化作為 out 參數傳遞的變數。然而,必須在方法返回之前為 out 參數賦值。
屬性不是變量,不能作為 out 參數傳遞。
網上有很多文章說ref 只傳值,out傳地址等等這種說法,好像不是非常的準確。以下是測試碼大家可以去試試:
public int RefValue(int i,ref int j) { int k = j; j =222; return i+k; } public int OutValue(int i, out int j) { j = 222; return i + j; } private void cmdRef_Click(object sender, EventArgs e) { int m = 0; MessageBox.Show(RefValue(1, ref m).ToString()); MessageBox.Show(m.ToString()); } private void cmdOut_Click(object sender, EventArgs e) { int m; MessageBox.Show(OutValue(1, out m).ToString()); MessageBox.Show(m.ToString()); }
總結一句,ref是有進有出,而out是只出不進。
2013年3月7日 星期四
【C#】INT,DOUBLE,BOOL 宣告成NULL值
Nullablex1 = null; Nullable x2 = null; Nullable x3 = null; //或 //test if (x1.HasValue) { Response.Write(x1.ToString()); } else { x1 = 1; Response.Write(x1.ToString()); }
2013年2月26日 星期二
【C#】DATETIME心得
1.yyyyMMdd的字串轉DateTime
var newDate = DateTime.ParseExact("20111120", "yyyyMMdd", CultureInfo.InvariantCulture);或
string str = "20111021"; string[] format = {"yyyyMMdd"}; DateTime date; if (DateTime.TryParseExact(str, format, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out date)) { //valid }2.常用函數
C# 常用日期時間函數(老用不熟) ,需要的朋友可以參考下。 //取當前年月日時分秒 currentTime=System.DateTime.Now; //取當前年 int 年=currentTime.Year; // 取當前月 int 月=currentTime.Month; // 取當前日 int 日=currentTime.Day; // 取當前時 int 時=currentTime.Hour; //取當前分 int 分=currentTime.Minute; // 取當前秒 int 秒=currentTime.Second; // 取當前毫秒 int 毫秒=currentTime.Millisecond; // 取中文日期顯示——年月日時分 string strY=currentTime.ToString("f"); //不顯示秒 // 取中文日期顯示_年月 string strYM=currentTime.ToString("y"); //取中文日期顯示_月日 string strMD=currentTime.ToString("m"); // 取當前年月日,格式為:2003-9-23 string strYMD=currentTime.ToString("d"); // 取當前時分,格式為:14:24 string strT=currentTime.ToString("t"); //今天 DateTime.Now.Date.ToShortDateString(); //昨天,就是今天的日期減一 DateTime.Now.AddDays(-1).ToShortDateString(); //明天 DateTime.Now.AddDays(1).ToShortDateString(); //本周(要知道本周的第一天就得先知道今天是星期幾,從而得知本周的第一天就是幾天前的//那一天,要注意的是這裏的每一周是從周日始至週六止 DateTime.Now.AddDays(Convert.ToDouble((0 - Convert.ToInt16(DateTime.Now.DayOfWeek)))).ToShortDateString(); DateTime.Now.AddDays(Convert.ToDouble((6 - Convert.ToInt16(DateTime.Now.DayOfWeek)))).ToShortDateString(); //如果你還不明白,再看一下中文顯示星期幾的方法就應該懂了 //由於DayOfWeek返回的是數字的星期幾,我們要把它轉換成漢字方便我們閱讀,有些人可能會用switch來一個一個地對照,其實不用那麼麻煩的 string[] Day = new string[] { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" }; Day[Convert.ToInt16(DateTime.Now.DayOfWeek)]; //上周,同理,一個周是7天,上周就是本周再減去7天,下周也是一樣 DateTime.Now.AddDays(Convert.ToDouble((0 - Convert.ToInt16(DateTime.Now.DayOfWeek))) - 7).ToShortDateString(); DateTime.Now.AddDays(Convert.ToDouble((6 - Convert.ToInt16(DateTime.Now.DayOfWeek))) - 7).ToShortDateString(); //下周 DateTime.Now.AddDays(Convert.ToDouble((0 - Convert.ToInt16(DateTime.Now.DayOfWeek))) + 7).ToShortDateString(); DateTime.Now.AddDays(Convert.ToDouble((6 - Convert.ToInt16(DateTime.Now.DayOfWeek))) + 7).ToShortDateString(); //本月,很多人都會說本月的第一天嘛肯定是1號,最後一天就是下個月一號再減一天。當然//這是對的 //一般的寫法 DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + "1"; //第一天 DateTime.Parse(DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + "1").AddMonths(1).AddDays(-1).ToShortDateString();//最後一天
2012年3月16日 星期五
【C#】 存取WORD中文字區域的文字
要寫一個簡單的程式去WORD去SEARCH一些文字方塊中的特定字串並取代新字串,再印出來
簡單的範例如下..
記得先參考Microsoft Word 12.0 Object library或Microsoft Word 13.0 Object library
或Microsoft Word 14.0 Object library(對映office版本)
簡單的範例如下..
記得先參考Microsoft Word 12.0 Object library或Microsoft Word 13.0 Object library
或Microsoft Word 14.0 Object library(對映office版本)
using System.IO; using System.Data.OleDb; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Collections; using System.Windows.Forms; using Word = Microsoft.Office.Interop.Word; using System.Reflection; using Microsoft.Office.Interop.Word; using System.Threading; /* 中略 */ #region 取代WORD主程式
#region 取代文字FUNCTION(被呼叫的FUN) public void exchange(string oldstring, string newstring, ref Word._Document oDoc,ref Word._Application oWord) { #region 文字區域 string oldStr = oldstring;//被取代的文字 string newStr = newstring;//要放入的文字 object replaceAll = Word.WdReplace.wdReplaceAll; object missing = Type.Missing; oWord.Selection.Find.ClearFormatting(); oWord.Selection.Find.Text = oldStr; oWord.Selection.Find.Replacement.ClearFormatting(); oWord.Selection.Find.Replacement.Text = newStr; oWord.Selection.Find.Execute( ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref replaceAll, ref missing, ref missing, ref missing, ref missing); #endregion #region 文本框 StoryRanges sr = oDoc.StoryRanges; foreach (Range r in sr) { Range r1 = r; if (WdStoryType.wdTextFrameStory == r.StoryType) { do { r1.Find.ClearFormatting(); r1.Find.Text = oldStr; r1.Find.Replacement.ClearFormatting(); r1.Find.Replacement.Text = newStr; r1.Find.Execute( ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref replaceAll, ref missing, ref missing, ref missing, ref missing); r1 = r1.NextStoryRange; } while (r1 != null); } } #endregion } #endregion //此為主程式 public void change_wordDOC(System.Data.DataTable dt,int NUM,string filenameDoc, string ADDRESS) { copy_doc(filenameDoc);//此為將要取代的文件複製到另一個資料夾再處理,省略內容.. string[] str_list = new string[] { "AAA", "BBB", "CCC", "DDD", "EEE", "FFF", "GGG", "HHH" };//比對WORD位置 object oMissing = System.Reflection.Missing.Value; Word._Application oWord; Word._Document oDoc; oWord = new Word.Application(); oWord.Visible = false;//背景處理不開啟word介面 // 打開文件: string filename_root = System.Windows.Forms.Application.StartupPath + @"\DOC2\" + filenameDoc; object fileName = System.Windows.Forms.Application.StartupPath + @"\DOC2\" + filenameDoc; oDoc = oWord.Documents.Open(ref fileName, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing); for (int i = 0; i < NUM; i++) { exchange(str_list[i].ToString(), dt.Rows[0][i].ToString(), ref oDoc, ref oWord);
//呼叫取代字串的函數 exchange(要被取代的字串,要取代的字串, 開啟Word._Document ,開啟的Word._Application)
} exchange("ADDRESS", ADDRESS, ref oDoc, ref oWord); //oDoc.PrintPreview();//可以顯示word預覽列印 oDoc.PrintOut(ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing); Thread.Sleep(3000); MessageBox.Show("列印完成"); oDoc.Close(ref oMissing, ref oMissing, ref oMissing);//關閉文件 oWord.Quit(ref oMissing, ref oMissing, ref oMissing);//關閉WORD } #endregion
2011年11月30日 星期三
【C#】使用ORACLE兩種寫SQL傳參數的方法
1.使用string.format方法
ExcuteForQuery方法
2.使用command的物件
ExcuteForQuery方法
#region 寫法1 DataTable ddt = new DataTable(); string ss = string.Format("SELECT * FROM UI_USER_GROUP WHERE USER_NAME='{1}'", "SHENG"); //{1}表示逗號後的第一個引數,{2}可以表示為逗號後第二個引數,以此類推 ddt = ExcuteForQuery(ss); if (ddt.Rows.Count > 0) { MsgBox("大於0");//自訂messagebox方法 } else { MsgBox("等於0"); } #endregion
ExcuteForQuery方法
public DataTable ExcuteForQuery(string sql) { DT = new DataTable();//建立datatable接收query的資料 using (OracleConnection conn = new OracleConnection("Data Source=orcl;User=SHENG;Password=1234")) //建立連線物件aaa, Data Source=IP/DB_NAME;User=XXXX;Password=XXXX { conn.Open();//開始連線 //建立od物件接收select結果 OracleDataAdapter OD = new OracleDataAdapter(sql, conn); OD.Fill(DT); //指定datagridview的datasource conn.Close();//結束連線 } return DT; }
2.使用command的物件
#region 寫法2 DataTable ddt2 = new DataTable(); string l_strExeSQL = "SELECT * FROM UI_USER_GROUP WHERE USER_NAME = :USERNAME"; OracleCommand g_scSql = new OracleCommand(l_strExeSQL); g_scSql.Parameters.Add("USERNAME", OracleType.VarChar).Value = "SHENG"; ddt2 = ExcuteForQuery(g_scSql); if (ddt2.Rows.Count > 0) { MsgBox("大於0");//自訂messagebox方法 } else { MsgBox("等於0"); } #endregion
ExcuteForQuery方法
public DataTable ExcuteForQuery(OracleCommand o_cmd) { DT = new DataTable();//建立datatable接收query的資料 using (OracleConnection conn = new OracleConnection("Data Source=orcl;User=SHENG;Password=1234"))//建立連線物件aaa, Data Source=IP/DB_NAME;User=XXXX;Password=XXXX { conn.Open();//開始連線 o_cmd.Connection = conn; //建立od物件接收select結果 OracleDataAdapter OD = new OracleDataAdapter(o_cmd); OD.Fill(DT); //指定datagridview的datasource conn.Close();//結束連線 } return DT; }
【ASP.NET】自訂MESSAGEBOX方法
asp.net沒有messagebox.show可以用
不過沒關係, 可以自己寫一個
網路上看到一個vb版, 改成c#版分享給大家
不過沒關係, 可以自己寫一個
網路上看到一個vb版, 改成c#版分享給大家
public void MsgBox(string Message) { string sScript = null; string sMessage = null; sMessage = Message.Replace("'", "\'"); //處理單引號 sMessage = sMessage.Replace(Environment.NewLine, "\\n"); //處理換行 sScript = string.Format("alert('{0}');", sMessage); ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", sScript, true); }
2011年10月5日 星期三
2011年9月28日 星期三
【C#】傳值呼叫與傳祉呼叫使用時機
傳祉呼叫寫法
CallRef(ref a, ref b);
public void CallRef(ref int a, ref int b) { ... }
傳值呼叫寫法
CallRef( a, b);
public void CallRef( int a, int b) { ... }
應用面:
寫法很簡單, 但是時機呢?什麼時候該用傳值或傳祉
1.當呼叫的方法是處理原本主程式中的參數時
使用傳值的話,不會改變原本的a,與b的數值,
如下列,在呼叫CallRef後還是a=10,b=10
ex:
int a =10,b=10; CallRef( a, b);
public void CallRef( int a, int b)
{
a=a+b;
b=b+a;
}
若使用傳祉,則呼叫CallRef後是a=20,b=20
ex: int a =10,b=10; CallRef(ref a,ref b); public void CallRef(ref int a, ref int b) { a=a+b; b=b+a; }
2.但是如果你呼叫的方法傳入的參數,和回傳的東西
是兩種不一樣的東西, 傳值傳祉都可以,但傳祉似乎會好一點
public Datatable CallRef( string SQL_CMD) {
...
DataTable DT=null;
return DT://傳回的為DataTable物件
}
string sql_cmd="SELECT * FROM MAIN";
DataTable dt=CallRef(sql_cmd);//傳入的參數為STRING
還有人想到什麼可以補充的嘛
2011年8月25日 星期四
【C#】刪除ACCESS資料列後, ACCESS容量太大
因為從C#內刪除資料後, 只是暫時的刪除, 所以你會看到一個什麼資料都沒有的DB還有100多MB的大小..所以DELETE後要從程式中再進行處理
首先先引用
using System.IO;
using JRO;
接下來在程式裡撰寫以下程式
string mdbPath = "C:\\DB_EQP.mdb";//資料庫路徑
if( !File.Exists(mdbPath) ) //检查数据库是否已存在
{
throw new Exception("資料庫不存在,無法壓縮");
}
//定義臨資料庫名稱
string temp = DateTime.Now.ToString("HH:mm:ss") + ".bak";
temp = temp.Split(':')[0].ToString() + temp.Split(':')[1].ToString() + temp.Split(':')[2].ToString();
temp = mdbPath.Substring(0, mdbPath.LastIndexOf("\\")+1) + temp;
//定義臨時資料庫路徑連接字串
string temp2 = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + temp;
//定義目標資料庫路徑連接字串
string mdbPath2 = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + mdbPath;
//新增一個JetEngineClass物件
JRO.JetEngineClass jt = new JRO.JetEngineClass();
//使用JetEngineClass物件的CompactDatabase方法壓縮資料庫
jt.CompactDatabase( mdbPath2, temp2 );
//覆蓋原本資料庫
File.Copy( temp, mdbPath, true );
//刪除臨時資料庫
File.Delete( temp );
首先先引用
using System.IO;
using JRO;
接下來在程式裡撰寫以下程式
string mdbPath = "C:\\DB_EQP.mdb";//資料庫路徑
if( !File.Exists(mdbPath) ) //检查数据库是否已存在
{
throw new Exception("資料庫不存在,無法壓縮");
}
//定義臨資料庫名稱
string temp = DateTime.Now.ToString("HH:mm:ss") + ".bak";
temp = temp.Split(':')[0].ToString() + temp.Split(':')[1].ToString() + temp.Split(':')[2].ToString();
temp = mdbPath.Substring(0, mdbPath.LastIndexOf("\\")+1) + temp;
//定義臨時資料庫路徑連接字串
string temp2 = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + temp;
//定義目標資料庫路徑連接字串
string mdbPath2 = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + mdbPath;
//新增一個JetEngineClass物件
JRO.JetEngineClass jt = new JRO.JetEngineClass();
//使用JetEngineClass物件的CompactDatabase方法壓縮資料庫
jt.CompactDatabase( mdbPath2, temp2 );
//覆蓋原本資料庫
File.Copy( temp, mdbPath, true );
//刪除臨時資料庫
File.Delete( temp );
2011年8月9日 星期二
[C#]開啟EXE檔並輸入EXE檔的參數
先USING System.Diagnostics;
在程式裡放入下列程式
System.Diagnostics.Process.Start("路徑", "參數");
在程式裡放入下列程式
System.Diagnostics.Process.Start("路徑", "參數");
2011年8月2日 星期二
2011年7月26日 星期二
[C#]checkedListBox 範例
1. 添加項目 checkedListBox1.Items.Add("藍色"); checkedListBox1.Items.Add("紅色"); checkedListBox1.Items.Add("黃色"); 2. 判斷第i項是否選中,選中為true,否則為false if(checkedListBox1.GetItemChecked(i)) { return true; } else { return false; } 3. 設置第i項是否選中 checkedListBox1.SetItemChecked(i, true); //true改為false為沒有選中。 4. 設置全選 添加一個名為select_all的checkbox控制項,由其控制checkedListBox是全選還是全不選。 private void select_all_CheckedChanged(object sender, EventArgs e) { if(select_all.Checked) { for (int j = 0; j < checkedListBox1.Items.Count; j++) checkedListBox1.SetItemChecked(j, true); } else { for (int j =0; j < checkedListBox1.Items.Count; j++) checkedListBox1.SetItemChecked(j, false); } } 5. 得到全部選中的值 ,並將選中的項的文字組合成為一個字串。 string strCollected = string.Empty; for (int i = 0; i < checkedListBox1.Items.Count; i++) { if (checkedListBox1.GetItemChecked(i)) { if (strCollected == string.Empty) { strCollected = checkedListBox1.GetItemText( checkedListBox1.Items[i]); } else { strCollected = strCollected + "/" + checkedListBox1. GetItemText(checkedListBox1.Items[i]); } } } 6. 設置CheckedListBox中第i項的Checked狀態 checkedListBox1.SetItemCheckState(i, CheckState.Checked); 7. private void checkBoxAll_CheckedChanged(object sender, EventArgs e) { if (checkBoxAll.Checked) { //被選擇了則將CheckedListBox中的所有條目都變為Checked狀態 for (int i = 0; i < checkedListBoxLayerControl.Items.Count; i++) { checkedListBoxLayerControl.SetItemCheckState(i, CheckState.Checked); } } else { //否則變成Unchecked狀態 for (int i = 0; i < checkedListBoxLayerControl.Items.Count; i++) { checkedListBoxLayerControl.SetItemCheckState(i, CheckState.Unchecked); } } } 8. checkedListBox 單選設置(代碼實現) private void chkl_ItemAuditing_ItemCheck(object sender, ItemCheckEventArgs e) { if (chkl_ItemAuditing.CheckedItems.Count > 0) { for (int i = 0; i < chkl_ItemAuditing.Items.Count; i++) { if (i != e.Index) { this.chkl_ItemAuditing.SetItemCheckState(i, System.Windows.Forms.CheckState.Unchecked); } } } } 9. checkedListBox1顯示一個資料庫中關鍵字對應的所有記錄 for (int i = 0; i < table.Rows.Count; i++) { string name = table.Rows["myname"].ToString(); string paw = table.Rows["mypaw"].ToString(); checkedListBox1.Items.Add(name + paw); } 10. for(i=0;i<CheckedListBox.Items.Count;i++) { if(CheckedListBox.GetItemText( CheckedListBox.Items)=="你得到的值") { CheckedListBox.SetItemChecked(i,true); } } 11. 清除checkedListBox1中所有的選項 for (int i = 0; i < checkedListBox1.Items.Count; i++) { checkedListBox1.Items.Clear(); } 12. //設置索引為index的項為選中狀態 for (int i = 0; i < checkedListBox1.Items.Count; i++) { checkedListBox1.SetItemChecked(i, true); } 13. for (int i = 0; i < checkedListBox1.Items.Count; i++) { if (checkedListBox1.GetSelected(i)) { MessageBox.Show(checkedListBox1.CheckedItems.ToString()); } } 14. //選中checkedListBox1所有的選項 for (int i = 0; i < checkedListBox1.Items.Count; i++) { checkedListBox1.SetItemCheckState(i, CheckState.Checked); } 15. for (int i = 0; i < checkedListBox1.Items.Count; i++) { //如果checkedListBox1的第i項被選中, //則顯示checkedListBox1對應的值 if (checkedListBox1.GetItemChecked(i)) { MessageBox.Show(checkedListBox1.Items.ToString()); } } 16. //反向選擇checkedListBox1的選項 for (int i = 0; i < checkedListBox1.Items.Count; i++) { if (checkedListBox1.GetItemChecked(i)) { checkedListBox1.SetItemChecked(i, false); } else { checkedListBox1.SetItemChecked(i, true); } } 17. //checkedListBox1中選定的項->checkedListBox2 for (int i = 0; i < checkedListBox1.CheckedItems.Count; i++) { checkedListBox2.Items.Add(this.checkedListBox1.CheckedItems); //remove是除去一個具體的值,不是index,注意了 this.checkedListBox1.Items.Remove( this.checkedListBox1.CheckedItems); } 18. CheckedlistBox控制項比較有用到兩個屬性分別為CheckOnClick為True:表示單擊就選中當前行,為False:要點兩下才 可以選中。(預設值為False)。還有一個屬性為ThreeDCheckBoxes為True:表示三維的選中標記,為False:表示表面的顯示標 記。(預設值為False)。 19. for (int i = 0; i < checkedListBox1.Items.Count; i++) { if (checkedListBox1.GetItemChecked(i)) { checkedListBox1.SelectedIndex = i;//利用SelectedValue取得Value值時,只能取得當前焦點項的值。所以要對整個CheckedListBox中的所有勾選項,讓其都 做一次焦點項才能取得所有勾選的項的值。 str+= checkedListBox1.SelectedValue; } } 20.綁定數據 checkedListBox1.DataSource = dt; checkedListBox1.DisplayMember = "item"; checkedListBox1.ValueMember = "code"; |
2011年7月25日 星期一
[C#]button.PerformClick() 失效
PerformClick()
呼叫這個方法, 可以不用點擊BUTTON就執行寫在BUTTON內的程式碼。
但今天早上一進公司就遇到一個BUG, 不管我怎麼呼叫這個方法都沒有反應,
後來總算找到了, 原來是我把BUTTON的ENABLE屬性設成FALSE, 只要設成FALSE,
再呼叫PerformClick(),等同於沒有點擊按鈕的意思,找這個BUG找了我一小時= =...
呼叫這個方法, 可以不用點擊BUTTON就執行寫在BUTTON內的程式碼。
但今天早上一進公司就遇到一個BUG, 不管我怎麼呼叫這個方法都沒有反應,
後來總算找到了, 原來是我把BUTTON的ENABLE屬性設成FALSE, 只要設成FALSE,
再呼叫PerformClick(),等同於沒有點擊按鈕的意思,找這個BUG找了我一小時= =...
2011年7月20日 星期三
2011年7月19日 星期二
[C#]DATAGRIDVIEW--CHECKBOX取消勾選
在DATAGRIDVIEW內的CHECKBOX勾選時取消勾選
1.在DATAGRIDVIEW上加入兩個事件
CellValueChanged以及CurrentCellDirtyStateChanged
2. 在CurrentCellDirtyStateChanged裡加入以下程式碼
if (this.dataGridView1.IsCurrentCellDirty) //有未提交的更//改
{
this.dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);
}
3. 在CellValueChanged事件里加入以下程式碼
DataGridViewCheckBoxCell dgvCheckBoxCell = null;
if (this.dataGridView1.Columns[e.ColumnIndex].Name.Equals("選取"))
//我的CHECKBOX欄位名稱為選取
{
dgvCheckBoxCell = this.dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex] as DataGridViewCheckBoxCell;/取得checkbox的ROW欄位
}
if (dgvCheckBoxCell.Value.ToString() == "True")
//以下程式碼會將CHECKBOX從勾選變成未勾選
{
DataGridViewCheckBoxCell cell = dataGridView1.Rows[e.RowIndex].Cells["選取"] as DataGridViewCheckBoxCell;
cell.EditingCellFormattedValue = false;
cell.EditingCellValueChanged = true;
cell.Value = cell.EditingCellFormattedValue;
return;
}
1.在DATAGRIDVIEW上加入兩個事件
CellValueChanged以及CurrentCellDirtyStateChanged
2. 在CurrentCellDirtyStateChanged裡加入以下程式碼
if (this.dataGridView1.IsCurrentCellDirty) //有未提交的更//改
{
this.dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);
}
3. 在CellValueChanged事件里加入以下程式碼
DataGridViewCheckBoxCell dgvCheckBoxCell = null;
if (this.dataGridView1.Columns[e.ColumnIndex].Name.Equals("選取"))
//我的CHECKBOX欄位名稱為選取
{
dgvCheckBoxCell = this.dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex] as DataGridViewCheckBoxCell;/取得checkbox的ROW欄位
}
if (dgvCheckBoxCell.Value.ToString() == "True")
//以下程式碼會將CHECKBOX從勾選變成未勾選
{
DataGridViewCheckBoxCell cell = dataGridView1.Rows[e.RowIndex].Cells["選取"] as DataGridViewCheckBoxCell;
cell.EditingCellFormattedValue = false;
cell.EditingCellValueChanged = true;
cell.Value = cell.EditingCellFormattedValue;
return;
}
[C#]執行緒寫log錯誤
寫程式難免要寫LOG檔來紀錄一些ERROR或流程
但是如果寫在多執行緒裡面的時候, 就會造成兩隻執行緒同時開啟同一個檔案的困境
程式會因為這樣子死掉, 爬了一下文, C#裡有內鍵LOCK這個東西, 來確保, 同時只能有一支程式
來讀寫文字檔寫入LOG
範列如下:
但是如果寫在多執行緒裡面的時候, 就會造成兩隻執行緒同時開啟同一個檔案的困境
程式會因為這樣子死掉, 爬了一下文, C#裡有內鍵LOCK這個東西, 來確保, 同時只能有一支程式
來讀寫文字檔寫入LOG
範列如下:
static object lockMe = new object();
public static void WriteLog(string sErrMsg)
{
lock (lockMe)
{
using (StreamWriter sw =
new StreamWriter(pathName + sErrorTime + extName, true))
{
sw.WriteLine(sErrMsg);
sw.Close();
}
}
}
2011年7月18日 星期一
[C#] 好用的BACKGROUNDWORKER
C#裡面可以執行背景程式的元件, 可以當作多執行緒使用(看有幾隻要RUN就建幾個)
相當的EASY直覺化的元件。
步驟1.拉出一個BACKGROUNDWORKER到你的FORM上
步驟2.在BACKGROUNDWORKER上按右鍵=>屬性, 切換事件頁, 新增兩個事件Dowork以及RunWorkerCompleted
步驟3.加入一個class, 裡面置放你所需要執行的背景程式
class FUNCTION
{
public int ADDNUM(int x )
{
X=X+1;
return X;
}
}
步驟4.在Dowork的事件裡新增以下程式碼
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
//執行FUNCTION
FUNCTION fn= (FUNCTION)e.Argument;
e.Result = fn.ADDNUM(this.x);
}
步驟5.在RunWorkerCompleted事件裡增加以下程式碼
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{ //當作業完成後要做的事放這裡
int value = (int)e.Result;//取得函數回傳值
Messagebox.Show(value.Tostring());
}
步驟6.在需要開始執行背景程式的地方, 加入以下的程式碼
FUNCTION fn= new FUNCTION();
backgroundWorker_1.RunWorkerAsync(fn);
步驟7. ENJOY
相當的EASY直覺化的元件。
步驟1.拉出一個BACKGROUNDWORKER到你的FORM上
步驟2.在BACKGROUNDWORKER上按右鍵=>屬性, 切換事件頁, 新增兩個事件Dowork以及RunWorkerCompleted
步驟3.加入一個class, 裡面置放你所需要執行的背景程式
class FUNCTION
{
public int ADDNUM(int x )
{
X=X+1;
return X;
}
}
步驟4.在Dowork的事件裡新增以下程式碼
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
//執行FUNCTION
FUNCTION fn= (FUNCTION)e.Argument;
e.Result = fn.ADDNUM(this.x);
}
步驟5.在RunWorkerCompleted事件裡增加以下程式碼
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{ //當作業完成後要做的事放這裡
int value = (int)e.Result;//取得函數回傳值
Messagebox.Show(value.Tostring());
}
步驟6.在需要開始執行背景程式的地方, 加入以下的程式碼
FUNCTION fn= new FUNCTION();
backgroundWorker_1.RunWorkerAsync(fn);
步驟7. ENJOY
2011年4月12日 星期二
【C# 】字串處理
顧名思意,String 類別就是來處理字串的應用
它提供了一堆靜態方法 (Static Method) 來處理字串相關
以下介紹一些平時很實用的功能
字串的比較
Compare 方法會回傳整數值,來表示兩個字串的關聯性
正數表示第一個字串大於第二個字串
負數表示第一個字串小於第二的字串
零值表示兩個字串相等
string.Compare("字串", "測試"); // result = -1
string.Compare("字串測試", "字串測試"); // result = 0
string.Compare("字串", "測試"); // result = -1
string.Compare("字串測試", "字串測試"); // result = 0
字串中搜尋字元或子字串
當我們必須想知道某字串中是否有特定字串或字元時
可以使用 String 類別的 IndexOf 方法來傳回特定字串 (字元) 在字串中的索引位置
另外,我們也可以利用 LastIndexOf 方法於字串中從後往前找到特定字串並回傳索引位置
PS. 索引位置由 0 開始
PS. 在 .NET Framework 下每個中文字都算一字元,而不再是 ASCII 時代的兩字元了
PS. LastIndexOf 方法和 IndexOf 一樣回傳索引位置,一樣搜尋特定字串,只不過 IndexOf 方法是由前往後找,但 LastIndexOf 方法是由後往前找
"字串測試字串測試".IndexOf("串"); // result = 1
"字串測試字串測試".IndexOf("串測"); // result = 1
"字串測試字串測試".LastIndexOf("串測"); // result = 5
"字串測試字串測試".IndexOf("串"); // result = 1
"字串測試字串測試".IndexOf("串測"); // result = 1
"字串測試字串測試".LastIndexOf("串測"); // result = 5
字串轉換大小寫
ToUpper 及 ToLower 方法可以將字串全部轉換成大寫或小寫
並將結果回傳成新的字串
"abcdABCD".ToUpper(); // result = "ABCDABCD"
"abcdABCD".ToLower(); // result = "abcdabcd"
"abcdABCD".ToUpper(); // result = "ABCDABCD"
"abcdABCD".ToLower(); // result = "abcdabcd"
去除或添加字串前後空白字元或特定字元
我們可以用 Trim 方法去除字串前後的空白字元
而 TrimStart 及 TrimEnd 可以只移除前後的空白字元
另外 Trim, TrimStart, TrimEnd 方法除了可以移除空白字元外,還可以移除一個或多個字元
"字字串串測測試試".Trim("字試".ToCharArray()); // result = "串串測測"
"字串測試".Trim("串字試".ToCharArray()); // result = "測"
"字串測試".TrimStart(new char[] { '試', '字', '串' }); // result = "測試"
"字串測試".TrimEnd("串試字".ToCharArray()); // result = "字串測"
"字字串串測測試試".Trim("字試".ToCharArray()); // result = "串串測測"
"字串測試".Trim("串字試".ToCharArray()); // result = "測"
"字串測試".TrimStart(new char[] { '試', '字', '串' }); // result = "測試"
"字串測試".TrimEnd("串試字".ToCharArray()); // result = "字串測"
字串前後添加空白字元或特定字元
PadLeft 及 PadRight 方法則和上例功能相反 - 將字串前後補上空白字元或特定字元
方法中第一個參數則是決定補上字元後的總長度
如果原字串就比第一個參數小了,則就不補上字元了
// 字串前補上 '@' 字元到長度 10
"字串測試".PadLeft(10, '@'); // result = "@@@@@@字串測試"
// 字串長度比 2 小,則不補上 '@' 字元
"字串測試".PadRight(2, '@'); // result = "字串測試"
// 字串前補上 '@' 字元到長度 10
"字串測試".PadLeft(10, '@'); // result = "@@@@@@字串測試"
// 字串長度比 2 小,則不補上 '@' 字元
"字串測試".PadRight(2, '@'); // result = "字串測試"
在字串中插入字串、移除字串和取代字串
我們可以用 Insert, Remove, Replace 來處理字串的插入、移除、取代
這三個方法用法還滿直覺簡單
PS. Remove 只可以移除指定位置的指定長度字串,而無法帶入要移除的字串
但是其實可以利用 Replace 來做指定字串的移除
"字串測試".Insert(2, "ABCD"); // result = "字串ABCD測試"
"字串測試".Remove(1, 2); // result = "字試"
"字串測試".Replace("串測", "ABCD"); // result = "字ABCD試"
"字串測試".Replace("串測", string.Empty); // result = "字試"
"字串測試".Insert(2, "ABCD"); // result = "字串ABCD測試"
"字串測試".Remove(1, 2); // result = "字試"
"字串測試".Replace("串測", "ABCD"); // result = "字ABCD試"
"字串測試".Replace("串測", string.Empty); // result = "字試"
串連字串陣列及分隔
這兩個方法 Join 及 Split 但很少人用但很實用
尤其是 join 方法,因為有許多組合方法可以取代它的功能
雖然 Join 其有所限制,如串連前必須得知所有的字串,而不能將字串持續串連下去
但其實在某些場合之下還滿好用的
PS. Join 方法遇到字串陣列中有空字串時,還是會串連進回傳的字串中
string.Join("+", new string[] { "一", "二", "三", "四", "五" }); // result = "一+二+三+四+五"
"一+二+三+四+五".Split("+"); // result = 字串陣列
string.Join("+", new string[] { "一", "二", "三", "四", "五" }); // result = "一+二+三+四+五"
"一+二+三+四+五".Split("+"); // result = 字串陣列
取得子字串
最後一個方法,也是很常用很實用的方法 - 取出子字串 Substring 方法
"字串測試".Substring(1, 2); // result = "串測"
它提供了一堆靜態方法 (Static Method) 來處理字串相關
以下介紹一些平時很實用的功能
字串的比較
Compare 方法會回傳整數值,來表示兩個字串的關聯性
正數表示第一個字串大於第二個字串
負數表示第一個字串小於第二的字串
零值表示兩個字串相等
string.Compare("字串", "測試"); // result = -1
string.Compare("字串測試", "字串測試"); // result = 0
string.Compare("字串", "測試"); // result = -1
string.Compare("字串測試", "字串測試"); // result = 0
字串中搜尋字元或子字串
當我們必須想知道某字串中是否有特定字串或字元時
可以使用 String 類別的 IndexOf 方法來傳回特定字串 (字元) 在字串中的索引位置
另外,我們也可以利用 LastIndexOf 方法於字串中從後往前找到特定字串並回傳索引位置
PS. 索引位置由 0 開始
PS. 在 .NET Framework 下每個中文字都算一字元,而不再是 ASCII 時代的兩字元了
PS. LastIndexOf 方法和 IndexOf 一樣回傳索引位置,一樣搜尋特定字串,只不過 IndexOf 方法是由前往後找,但 LastIndexOf 方法是由後往前找
"字串測試字串測試".IndexOf("串"); // result = 1
"字串測試字串測試".IndexOf("串測"); // result = 1
"字串測試字串測試".LastIndexOf("串測"); // result = 5
"字串測試字串測試".IndexOf("串"); // result = 1
"字串測試字串測試".IndexOf("串測"); // result = 1
"字串測試字串測試".LastIndexOf("串測"); // result = 5
字串轉換大小寫
ToUpper 及 ToLower 方法可以將字串全部轉換成大寫或小寫
並將結果回傳成新的字串
"abcdABCD".ToUpper(); // result = "ABCDABCD"
"abcdABCD".ToLower(); // result = "abcdabcd"
"abcdABCD".ToUpper(); // result = "ABCDABCD"
"abcdABCD".ToLower(); // result = "abcdabcd"
去除或添加字串前後空白字元或特定字元
我們可以用 Trim 方法去除字串前後的空白字元
而 TrimStart 及 TrimEnd 可以只移除前後的空白字元
另外 Trim, TrimStart, TrimEnd 方法除了可以移除空白字元外,還可以移除一個或多個字元
"字字串串測測試試".Trim("字試".ToCharArray()); // result = "串串測測"
"字串測試".Trim("串字試".ToCharArray()); // result = "測"
"字串測試".TrimStart(new char[] { '試', '字', '串' }); // result = "測試"
"字串測試".TrimEnd("串試字".ToCharArray()); // result = "字串測"
"字字串串測測試試".Trim("字試".ToCharArray()); // result = "串串測測"
"字串測試".Trim("串字試".ToCharArray()); // result = "測"
"字串測試".TrimStart(new char[] { '試', '字', '串' }); // result = "測試"
"字串測試".TrimEnd("串試字".ToCharArray()); // result = "字串測"
字串前後添加空白字元或特定字元
PadLeft 及 PadRight 方法則和上例功能相反 - 將字串前後補上空白字元或特定字元
方法中第一個參數則是決定補上字元後的總長度
如果原字串就比第一個參數小了,則就不補上字元了
// 字串前補上 '@' 字元到長度 10
"字串測試".PadLeft(10, '@'); // result = "@@@@@@字串測試"
// 字串長度比 2 小,則不補上 '@' 字元
"字串測試".PadRight(2, '@'); // result = "字串測試"
// 字串前補上 '@' 字元到長度 10
"字串測試".PadLeft(10, '@'); // result = "@@@@@@字串測試"
// 字串長度比 2 小,則不補上 '@' 字元
"字串測試".PadRight(2, '@'); // result = "字串測試"
在字串中插入字串、移除字串和取代字串
我們可以用 Insert, Remove, Replace 來處理字串的插入、移除、取代
這三個方法用法還滿直覺簡單
PS. Remove 只可以移除指定位置的指定長度字串,而無法帶入要移除的字串
但是其實可以利用 Replace 來做指定字串的移除
"字串測試".Insert(2, "ABCD"); // result = "字串ABCD測試"
"字串測試".Remove(1, 2); // result = "字試"
"字串測試".Replace("串測", "ABCD"); // result = "字ABCD試"
"字串測試".Replace("串測", string.Empty); // result = "字試"
"字串測試".Insert(2, "ABCD"); // result = "字串ABCD測試"
"字串測試".Remove(1, 2); // result = "字試"
"字串測試".Replace("串測", "ABCD"); // result = "字ABCD試"
"字串測試".Replace("串測", string.Empty); // result = "字試"
串連字串陣列及分隔
這兩個方法 Join 及 Split 但很少人用但很實用
尤其是 join 方法,因為有許多組合方法可以取代它的功能
雖然 Join 其有所限制,如串連前必須得知所有的字串,而不能將字串持續串連下去
但其實在某些場合之下還滿好用的
PS. Join 方法遇到字串陣列中有空字串時,還是會串連進回傳的字串中
string.Join("+", new string[] { "一", "二", "三", "四", "五" }); // result = "一+二+三+四+五"
"一+二+三+四+五".Split("+"); // result = 字串陣列
string.Join("+", new string[] { "一", "二", "三", "四", "五" }); // result = "一+二+三+四+五"
"一+二+三+四+五".Split("+"); // result = 字串陣列
取得子字串
最後一個方法,也是很常用很實用的方法 - 取出子字串 Substring 方法
"字串測試".Substring(1, 2); // result = "串測"
2011年3月12日 星期六
DATAGRIEVIEW驗證
1.单元格只能输入整数
private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
if (e.ColumnIndex == 4)
{
if (dataGridView1.Rows[e.RowIndex].IsNewRow) { return; }
dataGridView1.Rows[e.RowIndex].ErrorText = "";
int NewVal = 0;
if (e.FormattedValue.ToString().Trim() != "") //该列也可以为空
{
try
{
int.Parse(e.FormattedValue.ToString()); //判断输入的是否为Int类型的数字
//!int.TryParse(e.FormattedValue.ToString(), out newInteger) || newInteger < 0 || String.IsNullOrEmpty(e.FormattedValue.ToString()) } catch (Exception ex) { e.Cancel = true; }
}
}
}
2.单元格只能输入小数和整数
private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
if (e.ColumnIndex == 5) 为列名
{
dataGridView1.Rows[e.RowIndex].ErrorText = "";
int NewVal = 0;
if (e.FormattedValue.ToString().Trim() != "") //该列也可以为空
{
try
{
Double.Parse(e.FormattedValue.ToString()); //判断输入的是否为double类型的数字
}
catch (Exception ex)
{
e.Cancel = true;
}
}
}
}
3.单击单元格 处于编辑状态
private void dataGridView1_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
if (e.ColumnIndex == 4)
{
try
{
dataGridView1.Rows[e.RowIndex].ErrorText = "";
this.dataGridView1.CurrentCell = this.dataGridView1[4, e.RowIndex];
this.dataGridView1.BeginEdit(true);
}
catch
{
MessageBox.Show("输入格式不正确"); //验证在一起使用
}
}
}
}
DataGridView中禁止排序
DataGridView.Columns(i).SortMode = DataGridViewColumnSortMode.NotSortable ;
private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
if (e.ColumnIndex == 4)
{
if (dataGridView1.Rows[e.RowIndex].IsNewRow) { return; }
dataGridView1.Rows[e.RowIndex].ErrorText = "";
int NewVal = 0;
if (e.FormattedValue.ToString().Trim() != "") //该列也可以为空
{
try
{
int.Parse(e.FormattedValue.ToString()); //判断输入的是否为Int类型的数字
//!int.TryParse(e.FormattedValue.ToString(), out newInteger) || newInteger < 0 || String.IsNullOrEmpty(e.FormattedValue.ToString()) } catch (Exception ex) { e.Cancel = true; }
}
}
}
2.单元格只能输入小数和整数
private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
if (e.ColumnIndex == 5) 为列名
{
dataGridView1.Rows[e.RowIndex].ErrorText = "";
int NewVal = 0;
if (e.FormattedValue.ToString().Trim() != "") //该列也可以为空
{
try
{
Double.Parse(e.FormattedValue.ToString()); //判断输入的是否为double类型的数字
}
catch (Exception ex)
{
e.Cancel = true;
}
}
}
}
3.单击单元格 处于编辑状态
private void dataGridView1_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
{
if (e.ColumnIndex == 4)
{
try
{
dataGridView1.Rows[e.RowIndex].ErrorText = "";
this.dataGridView1.CurrentCell = this.dataGridView1[4, e.RowIndex];
this.dataGridView1.BeginEdit(true);
}
catch
{
MessageBox.Show("输入格式不正确"); //验证在一起使用
}
}
}
}
DataGridView中禁止排序
DataGridView.Columns(i).SortMode = DataGridViewColumnSortMode.NotSortable ;
訂閱:
文章 (Atom)