文章分類

C# (27) ASP.NET (13) SQL (7) ORACLE (5) JAVA (2) SQLSERVER2008 (2) 大家都在問的事 (2) ACCESS (1) ANDRIOD (1) JQUERY (1) python (1) 雜談 (1)

關於我自己

我的相片
程式初心者 JAVA, ASP.NET, C# ,SQL

2011年7月21日 星期四

[ORACLE]建資料表時使用自動編號

ORACLE 並沒有像ACCESS和MS-SQL等資料庫有提供自動編號功能,
讓習慣用流水號當主鍵的我覺得十分不習習慣
爬了文發現了其實可以用別的方式來達成
在ORACLE裡下以下的語法

    CREATE SEQUENCE MySEQUENCE
    INCREMENT BY 1  -- 每次加幾個
    START WITH 1    -- 從1開始計數
    NOMAXVALUE      -- 不設置最大值
    NOCYCLE         -- 一直累加,不循環
    CACHE 10;

或自行定義最大最小值

CREATE SEQUENCE MySEQUENCE
MINVALUE 1                        --最小值
MAXVALUE 10000000      -最大值
START WITH 1                     -- 從1開始計數
INCREMENT BY 1               -每次加1
NOCACHE







接下來只要帶INSERT SQL時動手腳就好了,就可以自動編號了!

INSERT INTO emp VALUES 
(MySEQUENCE.nextval, 'LEWIS', 'CLERK',7902, SYSDATE, 1200, NULL, 20);

2011年7月20日 星期三

[C#]移除字串最後一個字元

 string op="01234";

 op= op.Substring(0, op.Length - 2);

Messagebox.show(op);

結果==>012

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;                
                 }

[C#]執行緒寫log錯誤

寫程式難免要寫LOG檔來紀錄一些ERROR或流程
但是如果寫在多執行緒裡面的時候, 就會造成兩隻執行緒同時開啟同一個檔案的困境
程式會因為這樣子死掉, 爬了一下文, 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

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 = "串測"

2011年3月21日 星期一

datagridview的checkbox列,当修改checkbox状态时实时获得其状态值

datagridview的checkbox列,当修改checkbox状态时实时获得其状态值

不知道大家有没有这样的经验,当点击或者取消datagridview的checkbox列时,比较难获得其状态是选中还是未选中,进而不好进行其它操作,下面就列出它的解决办法:

主要用到了datagridview的CurrentCellDirtyStateChanged和CellValueChanged两个事件

CurrentCellDirtyStateChanged事件是提交对checkbox状态的修改

CellValueChanged事件是当状态提交后,也就是单元格值改变后做一些其它的操作,这里是将checkbox列的true或false状态作为tooptiptext属性设置到同一行的button列

CurrentCellDirtyStateChanged事件代码 :


private void dataGridView1_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
if (this.dataGridView1.IsCurrentCellDirty) //有未提交的更//改
{
this.dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);
}
}

CellValueChanged事件代码 :


private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
if (this.dataGridView1.Columns[e.ColumnIndex].Name.Equals("gender"))
{
DataGridViewButtonCell dgvButtonCell
= this.dataGridView1.Rows[e.RowIndex].Cells["btn"] as DataGridViewButtonCell;//获得button列单元格
DataGridViewCheckBoxCell dgvCheckBoxCell = this.dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex] as DataGridViewCheckBoxCell;//获得checkbox列单元格
dgvButtonCell.ToolTipText = dgvCheckBoxCell.Value.ToString();//赋值
}
}

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 ;

2011年2月7日 星期一

C# 字符、字符串过滤,只能输入数字、中文、英文、大写、小写



private void TextBox1_KeyPress(object sender, KeyPressEventArgs e) //文本框输入字符过滤
{

if (Convert.ToInt32(e.KeyChar) >= 48 && Convert.ToInt32(e.KeyChar) < style="word-break: break-all; line-height: normal !important; "> //(Convert.ToInt32(e.KeyChar) >= 65 && Convert.ToInt32(e.KeyChar) < style="word-break: break-all; line-height: normal !important; "> //(Convert.ToInt32(e.KeyChar) >= 97 && Convert.ToInt32(e.KeyChar) < style="word-break: break-all; line-height: normal !important; "> //(Convert.ToInt32(e.KeyChar) == 46) || //包括.
//(Convert.ToInt32(e.KeyChar) == 32) || //包括空格
//(Convert.ToInt32(e.KeyChar) == 64) || //包括@
//(Convert.ToInt32(e.KeyChar) > 127) || //包括中文
Convert.ToInt32(e.KeyChar) == 8) //包括退格
{
}
else
{
e.Handled = true;
}

public static bool ReplaceCodes(String Temp) //检查字符串过滤方法
{
string s = Temp;
int l = s.Length;
char[] buf = s.ToCharArray();
string tmp = string.Empty;
for (int k = 0; k < style="word-break: break-all; line-height: normal !important; "> {
if ((Convert.ToInt32(buf[k]) >= 48 && Convert.ToInt32(buf[k]) < style="word-break: break-all; line-height: normal !important; "> //(Convert.ToInt32(buf[k]) >= 65 && Convert.ToInt32(buf[k]) < style="word-break: break-all; line-height: normal !important; "> //(Convert.ToInt32(buf[k]) >= 97 && Convert.ToInt32(buf[k]) < style="word-break: break-all; line-height: normal !important; "> //(Convert.ToInt32(buf[k]) == 46) || //.
//(Convert.ToInt32(buf[k]) == 32) || //空格
//(Convert.ToInt32(buf[k]) == 64) || //@
//(Convert.ToInt32(buf[k]) > 127) || //中文
//(Convert.ToInt32(buf[k]) == 8)) //退格
{
tmp += buf[k].ToString();
}
}
if (tmp.Length != l)
{
// Util.info("请输入正确整数数字!");
//Temp = tmp;
return false;
}
else
return true;
}

2010年12月26日 星期日

【C#】 SQL連線

SqlConnection _MSSqlConn; //宣告_MSSqlConn為MSSQL資料庫連結
SqlCommand _MSSqlCmd; //宣告_MSSqlCmd為MSSQL資料庫Command
SqlDataReader _MSSqlDR; //宣告_MSSqlDR為MSSQL資料庫DataReader
OleDbConnection _OleDbConn; //宣告_OleDbConn為Access資料庫連結
OleDbCommand _OleDbCmd; //宣告_OleDbCmd為Access資料庫Command
OleDbDataReader _OleDbDR; //宣告_OleDbDR為Access資料庫DataReader
string _ConnStr; //宣告_ConnStr為字串

/*=====Connection是一個與資料庫建立連線的用法=====*/
//SQLServer-Connection
_ConnStr = "Data Source=(local);Database=資料庫名稱;User ID=帳號;Password=密碼";
_MSSqlConn = new SqlConnection(_ConnStr);
//Access-Connection
_ConnStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=資料庫名稱;Jet OLEDB:Database Password=密碼";
_OleDbConn = new OleDbConnection(_ConnStr);

/*=====ExecuteNonQuery是一個單純做新增修改刪除的方法=====*/
//SQLServer-ExecuteNonQuery用法
_MSSqlConn.Open();
_MSSqlCmd = new SqlCommand(SQL語法,_MSSqlConn);
_MSSqlCmd.ExecuteNonQuery();
_MSSqlConn.Close();
//ACCESS-ExecuteNonQuery用法
_OleDbConn.Open();
_OleDbCmd = new OleDbCommand(SQL語法,_OleDbConn);
_OleDbCmd.ExecuteNonQuery();
_OleDbConn.Close();

/*=====DataReader是一個順向讀取資料庫的方法,優點速度快,缺點無法做到分頁的功能=====*/
//SQLServer-DataReader用法
_MSSqlConn.Open();
_MSSqlCmd = new SqlCommand(SQL語法,_MSSqlConn);
_MSSqlDR=_MSSqlCmd.ExecuteReader();
_MSSqlDR.Close(); //完成工作時必須將它關閉,否則其他物件就無法使用該連線
_MSSqlConn.Close(); //關閉Connection的連線
//ACCESS-DataReader用法
_OleDbConn.Open();
_OleDbCmd = new OleDbCommand(SQL語法,_OleDbConn);
_OleDbDR=_OleDbCmd.ExecuteReader();
_OleDbDR.Close(); //完成工作時必須將它關閉,否則其他物件就無法使用該連線
_OleDbConn.Close(); //關閉Connection的連線

/*=====DataSet為一個離線,資料驅動應用程式的核心,是完整資料集的記憶體內之代表,包括連線,關係和限制=====*/
//SQLServer-DataSet用法
DataSet DS=new DataSet(); //建立一個資料集的方法
SqlDataAdapter SqlAda = new SqlDataAdapter(SQL語法,_MSSqlConn); //建立資料庫接和器
SqlAda.Fill(DS,資料表名稱); //最後透過接和器將資料填入(Fill)資料集裡面,並將填入到資料集的表格取名

//ACCESS-DataSet用法
DataSet DS=new DataSet(); //建立一個資料集的方法
OleDbDataAdapter OleDbAda = new OleDbDataAdapter(SQL語法,_OleDbConn);//建立資料庫接和器
OleDbAda.Fill(DS,資料表名稱); //最後透過接和器將資料填入(Fill)資料集裡面,並將填入到資料集的表格取名