常用的C#小功能集锦
-
动态获取系统当前时间**
- 使用DateTime结构的Now静态属性返回当前系统时间
DateTime P_dt = DateTime.Now;
string P_str_dt = P_dt.Tostring( ); -
根据两个时间自动计算二个时间的差**
- 通过调用DateAndTime类的DateDiff静态方法来计算两
个日期的差从而得到工龄。
DateDiff(DateInterval Internal, DateTime Date1, DateTime Date2, FirstDay of Week Day of Week, FirsWeek of Year Week of Year);
参数 | 描述 |
---|---|
Internal | DateInterval枚举值,指定Date1与Date2时间间隔天数 |
Date1 | 计算中使用的第一个时间 |
Date2 | 计算中使用的第二个时间 |
DayofWeek | 用于指定一周的第一天,默认时FirstDayofWeek.Sundy |
Week of Year | 用于指定一年的第一周,默认时FirstWeek of Year.Jan1 |
具体用法:由于DateDiff时VB中的方法,所以要先添加VB程序集的引用。在添加引用菜单栏下添加 Microsoft.VisualBasic程序集的引用,同时在代码中添加命名空间的引用“Using Microsoft.VisualBasic;”
示例代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.VisualBasic;
namespace 获取系统时间测试
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show("间隔" + DateAndTime.DateDiff(DateInterval.Day, dtPicker1.Value,
dtPicker2.Value, FirstDayOfWeek.Sunday, FirstWeekOfYear.Jan1).ToString() + "天", "间隔时间");
}
}
}
使用TimeSpan对象获取时间间隔**
- 使用TimeSpan对象可以方便的获取两个时间间隔。两个时间信息相减会得到一个TimeSpan对象,通过TimeSpan对象的Day、Hours、Minutes、Seconds、Milliseconds属性分别得到时间的天、时、分、秒、毫秒数。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace 获取系统时间测试
{
public partial class GetTime_Form : Form
{
public GetTime_Form()
{
InitializeComponent();
}
private DateTime G_DateTime_First, G_DateTime_Second; //定义了两个时间字段
private void btnTime1_Click(object sender, EventArgs e)
{
G_DateTime_First = DateTime.Now;
txtDateTime1.Text = G_DateTime_First.ToString("year年M月d日H时m分s秒fff毫秒");
}
private void btnTime2_Click(object sender, EventArgs e)
{
G_DateTime_Second = DateTime.Now;
txtDateTime2.Text = G_DateTime_Second.ToString("year年M月d日H时m分s秒fff毫秒");
}
private void btnTim3_Click(object sender, EventArgs e)
{
TimeSpan P_timespan_temp =
G_DateTime_First > G_DateTime_Second ?
G_DateTime_First - G_DateTime_Second :
G_DateTime_Second - G_DateTime_First;
txtResut.Text = string.Format(
"时间的间隔:{0}天{1}时{2}分{3}秒{4}毫秒",
P_timespan_temp.Days, P_timespan_temp.Hours,
P_timespan_temp.Minutes,P_timespan_temp.Seconds,
P_timespan_temp.Milliseconds);
}
}
}
常用数字验证技巧
使用正则表达式验证电话号码
本例子用到了Regex类的IsMatch方法。Regex类的IsMatch方法用于指示正则表达式使用Pattern参数中指定的正则表达式是否在输入字符串中找到匹配项,格式如下:
**public static bool IsMatch(string input,string pattern)**
参数说明
参数 | 说明 |
---|---|
input | 字符串对象,表示要搜索匹配项的字符串 |
pattern | 字符串对象,表示要匹配的正则表达式模式 |
bool | 返回布尔量,如果正则表达式找到匹配项,则返回True,否则返回False |
在验证电话号码时用到了正则表达式:
@"^(\d{3,4}-)?\d{6,8}$"
参数 | 描述 |
---|---|
^ | 正则表达式中匹配位置的元字符,用于匹配行首 |
$ | 正则表达式中匹配位置的元字符,用于匹配行尾 |
- | 前后的连接符 |
{3,4 } | 匹配的类容格式为3到4位数 |
{6,8 } | 匹配的类容格式为6到8位数 |
先建立一个Telephone类,在Telephone类中定义IsTelephone方法。当要使用验证电话号码时调用IsTelephone这个方法即可。
public class Telephone
{
public bool IsTelephone(string str_telephone)
{
return System.Text.RegularExpressions.Regex.IsMatch(str_telephone, @"^(\d{3,4}-)?\d{6,8}$");
}
}
以下示例代码就是在Form里调用Telephone类中的IsTelephone方法去验证电话号码格式的。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace 获取系统时间测试
{
public partial class IsTelephoneForm : Form
{
public IsTelephoneForm()
{
InitializeComponent();
}
private void btnSearch_Click(object sender, EventArgs e)
{
string str = textBox1.Text;
Telephone tel = new Telephone(); //给Telephone类实例化一个对象
bool T = tel.IsTelephone(str); //在Telephone类中调用IsTelephone方法
if (T == true)
{
MessageBox.Show("输入的格式正确!");
}
else
{
MessageBox.Show("输入的电话格式不对!");
}
}
}
}
使用正则表达式验证输入密码的条件
使用方法与电话号码类似,也是要先建立一个Regex类的IsMatch方法。
public bool IsPassword(string str_password)
{
return System.Text.RegularExpressions.Regex.IsMatch(str_password, @"^[A-Za-z]+[0-9]");
}
在验证输入密码的条件时用到了正则表达式:
@"[A-Za-z] + [0,9]"
参数 | 描述 |
---|---|
[A-Za-z] | 匹配大小写字母 |
[0,9] } | 匹配数字 |
+ | 匹配一个到多个大小写字母 |
使用正则表达式验证邮政编码
使用方法与电话号码类似,也是要先建立一个Regex类的IsMatch方法。
public bool IsPostacode(string str_postacode) //使用正则表达式验证邮政编码的方法
{
return System.Text.RegularExpressions.Regex.IsMatch(str_postacode, @"^(\d{6}$");
}
使用正则表达式验证邮政编码时用到了正则表达式:
@"^\d{6}$"
参数 | 描述 |
---|---|
^] | 匹配行开始 |
$ } | 匹配行结束 |
\d | 匹配数字 |
{6} | 输入的数字为6位 |
系统登录示例
#region
private void btnLogin_Click(object sender, EventArgs e)
{
string strName = txtUserId.Text;
string strPwd = txtPwd.Text;
if (string.IsNullOrEmpty(strName))
{
MessageBox.Show("用户名不能为空", "提示",MessageBoxButtons.OK,
MessageBoxIcon.Information);
txtUserId.Focus();
return;
}
if (string.IsNullOrEmpty(strPwd))
{
MessageBox.Show("密码不能为空", "提示", MessageBoxButtons.OK,
MessageBoxIcon.Information);
txtPwd.Focus();
return;
}
string ConnctionAddreas = "Data Source =.;Initial Catalog=WareHouseManagementSystem;Integrated Security=True";
string user_id = txtUserId.Text.Trim(); //获取ID
string user_pwd = txtPwd.Text.Trim(); //获取密码
using (SqlConnection conn = new SqlConnection(ConnctionAddreas))
{
conn.Open();
string sql = "select userPwd from Users where [userId] ='" + user_id + "'and [userPwd] = '" + user_pwd + "'";
SqlCommand cmd = new SqlCommand(sql, conn);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
MessageBox.Show("欢迎登录酒店管理系统!");
this.Hide();
MainForm frm = new MainForm();
frm.Show();
}
else
{
MessageBox.Show("密码或用户名错误", "提示", MessageBoxButtons.OK,
MessageBoxIcon.Information);
txtUserId.Clear();
txtPwd.Clear();
txtUserId.Focus();
}
}
}
private void LoginForm_FormClosing(object sender, FormClosingEventArgs e)
{
if (MessageBox.Show("将要关闭窗口", "提示", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
e.Cancel = false;
}
else
{
e.Cancel = true;
}
}
private void btnExit_Click_1(object sender, EventArgs e)
{
Application.Exit();
}
}
}
#endregion