目前分類:C# (12)

瀏覽方式: 標題列表 簡短摘要
語言:C#
功能:string.Substring(startIndex, length)改良
原因:當StartIndex + length > string.Length時會發生錯誤,但程式執行時有時不知道字長度,造成錯誤,很麻煩,只好自己改良了
語法:
 public static string SubString(string strData, int startIndex, int length) 
        {
            int intLen = strData.Length;
            int intSubLen = intLen - startIndex;
            string strReturn; 

            if (length == 0)
                strReturn = "";
            else
            {
                if (intLen <= startIndex)
                    strReturn = "";
                else
                {
                    if (length > intSubLen)
                        length = intSubLen;

                    strReturn = strData.Substring(startIndex, length);
                }
            }
            return strReturn;
        }


範例:

string strReturn = "";
string strData = "0123456789";

strReturn = Substring(strData, 0, 0 );               // ""
strReturn = Substring(strData, 0, 12);             // "0123456789"
strRetrun = Substring(strData, 13, 10);          // ""
strReturn = Substring(strData, 9, 3);              // "9"
strReturn = Substring(strData, 0, 3);             //"012"

janema66 發表在 痞客邦 留言(1) 人氣()

語言:C#
功能:無條件捨去
語法:

public static double NoRound(double num, int post)
  {
         double nReturn;
         double nPow;
          if (post <= 0 )
          {
              nReturn = Math.Floor(num);
          }
          else
          {
              nPow = Math.Pow(10, post);
              nReturn = Math.Floor(num * nPow)/nPow;
          }
          return nReturn;
}

janema66 發表在 痞客邦 留言(2) 人氣()

語言:C#

 public static string ConvertDateToString(string strDate)
   {
        return DateTime.ParseExact(strDate, "yyyy/MM/dd", CultureInfo.CurrentCulture).ToString("yyyyMMdd");
   }

   public static string ConvertStringToDate(string strDate)
    {
        return DateTime.ParseExact(strDate, "yyyyMMdd", CultureInfo.CurrentCulture).ToString("yyyy/MM/dd");
    }

janema66 發表在 痞客邦 留言(0) 人氣()

 VB.ET及C# 程式碼轉換
推薦此網站:
http://labs.developerfusion.co.uk/

janema66 發表在 痞客邦 留言(0) 人氣()

語言: C#
功能: FTP下載檔案
語法:

        public static StreamReader FtpDownLoad(Uri UriFpt, string strUserName, string strPassword)
        {
            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(UriFpt);
            request.Method = WebRequestMethods.Ftp.DownloadFile;

            request.Credentials = new NetworkCredential(strUserName, strPassword);
            FtpWebResponse response = (FtpWebResponse)request.GetResponse();
            Stream responseStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(responseStream, Encoding.Default);
            return reader;
        }


呼叫時
 Uri  UriFtp = new Uri ("ftp:// ip / filename ")
string  strUserName = "username";
string  strPassword = "password";

StreamReader reader =  FtpDownLoad(UriFtp, strUserName, strPassword);
   while (reader.Peek() >= 0)
    {
           StringBuilder s = new StringBuilder();
           s.Append(reader.ReadLine());
           
   }
 reader.Close();

janema66 發表在 痞客邦 留言(0) 人氣()

Form1:
BackgroundImage:挑一個不規則型狀的圖片
BackgroundImageLayoutStretch
FormBorderStyle :none

重點在下面二個屬性:
設為圖片的背景色,且都相同
BackColor:圖片的背景顏色
TransparencyKey:圖片的背景顏色
  當指派 ColorTransparencyKey 屬性時,具有相同 BackColor 的表單區域將透明地顯示。


表單在超過色彩32bit就會有問題,解決方法:

 private void Form1_Load(object sender, EventArgs e)
 {
     ((Bitmap)this.BackgroundImage).MakeTransparent();
 }



不規則表單,沒有邊框,表單不會移動,不能關閉

表單關閉作法:

 private void Form1_DoubleClick(object sender, EventArgs e)
 {
      this.Close();
 }


移動表單作法:

bool start = false;
int x, y;
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
     start = true;
     this.x = e.X;
     this.y = e.Y;
}

private void Form1_MouseMove(object sender, MouseEventArgs e)
{
     if (start)
     {
         this.Location = new Point(this.Location.X + e.X - x, this.Location.Y + e.Y - y);
      }
}

private void Form1_MouseUp(object sender, MouseEventArgs e)
{
     start = false;
}



janema66 發表在 痞客邦 留言(1) 人氣()

語言:C#  
功能:將畫面所有TextBox都清為空白


輸入畫面如上,使用者將剛才輸入項全部清空

        private void button1_Click(object sender, EventArgs e)
        {
            foreach (Control c in Controls)
            {
                if (c is TextBox)
                    c.Text = "";
            }

janema66 發表在 痞客邦 留言(0) 人氣()

C# TextBox電子郵件驗證

private void TextBox1_Validating(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (TextBox1.Text==string.Empty)
                errorProvider1.SetError(TextBox1, "");
            else
                if (!(Regex.IsMatch(TextBox1.Text,
                              @"^([a-zA-Z0-9_\-])([a-zA-Z0-9_\-\.]*)@(\[((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}|((([a-zA-Z0-9\-]+)\.)+))([a-zA-Z]{2,}|(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\])$")))
                {
                    errorProvider1.SetError(TextBox1, "電子郵件地址務必採用 abc@cccc.ccc.cc 的格式。");
                    e.Cancel = true;
                }
                else
                {
                    errorProvider1.SetError(TextBox1, "");
                    e.Cancel = false;
                }
        }

janema66 發表在 痞客邦 留言(0) 人氣()

C#  TextBox只能夠輸入數字及小數點

private void InitializeComponent()

 this.TextBox1.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.TextBoxF_32B_2_KeyPress);


 private void TextBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
        {
            if (e.KeyChar.CompareTo('\b') == 0)
                e.Handled = false;
            else if ((e.KeyChar.CompareTo('0') < 0 || e.KeyChar.CompareTo('9') > 0) && !(e.KeyChar.CompareTo('.') == 0)) //比較輸入值的範圍是否超出數字
                e.Handled = true;// Handled 為是否鎖住輸入

        }

janema66 發表在 痞客邦 留言(0) 人氣()

C# 使用ClickOnce 部署
無法指定安裝路徑,安裝後Access資料庫存放於何處
儲存在使用者 [Documents and Settings] 資料夾中的資料目錄

若想要知道正確路徑,程式碼:
if (ApplicationDeployment.IsNetworkDeployed)
 {
    ApplicationDeployment ad = ApplicationDeployment.CurrentDeployment;
    textBox1.Text = ad.DataDirectory.ToString();
 }


[Documents and Settings] \UserName\Local Settings\Apps\2.0\Data\.................目錄下

janema66 發表在 痞客邦 留言(1) 人氣()

DataGridView
設定不能新增.修改.刪除 

方法:
this.dataGridView1.AllowUserToAddRows = false;
this.dataGridView1.AllowUserToDeleteRows = false;




設定不能修改,則將畫面中的啟用編輯取消,即可

janema66 發表在 痞客邦 留言(0) 人氣()

C#

錯誤訊息:
並未將物件參考設定為物件的執行個體

原來程式:
OleDbCommand queryCMD = new OleDbCommand();
queryCMD.Connection = myConnection;
queryCMD.CommandText = "SELECT 密碼 FROM A01_USER WHERE 使用者名稱 = @ID";
queryCMD.Parameters.Add("@ID", OleDbType.Char, 10);
queryCMD.Parameters["@ID"].Value = txtName.Text;
myConnection.Open();
string mPassword = queryCMD.ExecuteScalar().ToString();
---->錯誤發生於找不到任何資料時

原因:
呼叫方法前先檢查該物件是否為null

更改後程式
myConnection.Open();
object obj = queryCMD.ExecuteScalar();
myConnection.Close();
if (obj == null)
 {
      MessageBox.Show("使用者名稱錯誤", "系統登入");
 }
else
  {
      string mPassword = obj.ToString(); 
   }

janema66 發表在 痞客邦 留言(0) 人氣()