public class WinformStyle
{
#region 定制窗体样式
/// <summary>
/// 定制窗体(Lable{背景:天蓝色},TextBox{文本为空},ComboBox{文本不可编辑},DateTimePicker{大小:190,31})
/// </summary>
/// <param name="parentControl">父级容器</param>
/// <param name="frmFont">字体大小</param>
public static void MadeForm(Control parentControl, EFormFont frmFont)
{
foreach (Control ctl in parentControl.Controls)
{
if (ctl is Label)
{
//(ctl as Label).Tag = "9999";
}
if (ctl is TextBox)
{
(ctl as TextBox).Text = string.Empty;
}
if (ctl is ComboBox)
{
(ctl as ComboBox).DropDownStyle = ComboBoxStyle.DropDownList;
}
if (ctl is DateTimePicker)
{
if (frmFont == EFormFont.BigFont)
{ (ctl as DateTimePicker).Size = new Size(190, 31); }
}
if (ctl is DataGridView)
{
DataGridView dgv = ctl as DataGridView;
//第一列如果为复选框,则设为可编辑
foreach (DataGridViewColumn column in dgv.Columns)
{
if (column.Index == 0 && column.CellTemplate is DataGridViewCheckBoxCell)
{ column.ReadOnly = false; }
else
{ column.ReadOnly = true; }
}
dgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;//列宽自动排列
dgv.RowHeadersVisible = false;
dgv.AllowUserToAddRows = false;
dgv.AllowUserToDeleteRows = false;
//dgv.AllowUserToResizeColumns = false;
dgv.AllowUserToResizeRows = false;
dgv.MultiSelect = false;
dgv.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dgv.AutoGenerateColumns = false;
dgv.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
dgv.RowsDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
dgv.RowsDefaultCellStyle.Font = new Font("宋体", 12, FontStyle.Bold);
dgv.RowTemplate.Height = 35;
dgv.CellClick += new DataGridViewCellEventHandler(dgvRoleList_CellContentClick);
dgv.DataBindingComplete += new DataGridViewBindingCompleteEventHandler(dgvSchoolList_DataBindingComplete);
//dgv.DataSourceChanged += new EventHandler(dataGridView_DataSourceChanged);
//dgv.CellValueChanged += new DataGridViewCellEventHandler(dataGridView_CellValueChanged);
}
if (frmFont == EFormFont.BigFont)
{
ctl.Font = new Font("宋体", 15.75F, FontStyle.Bold, GraphicsUnit.Point, ((byte)(134)));
}
if (ctl is Form || ctl is Panel || ctl is GroupBox || ctl is TabControl || ctl is TableLayoutPanel || ctl is FlowLayoutPanel)
{
MadeForm(ctl);
}
//ctl.ContextMenu = new ContextMenu();
}
}
/// <summary>
/// 定制窗体 -kkzy
/// </summary>
/// <param name="parentControl">父级容器</param>
public static void MadeForm(Control parentControl)
{
if (parentControl is Form)
{
(parentControl as Form).MaximizeBox = false; //隐藏最大化按钮
(parentControl as Form).MinimizeBox = false; //隐藏最小化按钮
(parentControl as Form).FormBorderStyle = FormBorderStyle.FixedSingle; //窗体固定,不可拖曳
(parentControl as Form).StartPosition = FormStartPosition.CenterScreen; //窗体居中
}
parentControl.BackColor = Color.MintCream; //控件背景色
MadeForm(parentControl, EFormFont.SmallFont);
}
/// <summary>
/// 定制窗体 -kkzy
/// </summary>
/// <param name="parentControl">父级容器</param>
public static void MadeFormNew(Control parentControl)
{
if (parentControl is Form)
{
(parentControl as Form).MaximizeBox = false; //隐藏最大化按钮
(parentControl as Form).MinimizeBox = false; //隐藏最小化按钮
(parentControl as Form).FormBorderStyle = FormBorderStyle.FixedSingle; //窗体固定,不可拖曳
(parentControl as Form).StartPosition = FormStartPosition.CenterScreen; //窗体居中
}
parentControl.BackColor = Color.MintCream; //控件背景色
MadeFormNew(parentControl, EFormFont.SmallFont);
}
/// <summary>
/// 定制窗体(Lable{背景:天蓝色},TextBox{文本为空},ComboBox{文本不可编辑},DateTimePicker{大小:190,31})
/// </summary>
/// <param name="parentControl">父级容器</param>
/// <param name="frmFont">字体大小</param>
public static void MadeFormNew(Control parentControl, EFormFont frmFont)
{
foreach (Control ctl in parentControl.Controls)
{
if (ctl is Label)
{
//(ctl as Label).Tag = "9999";
}
if (ctl is TextBox)
{
(ctl as TextBox).Text = string.Empty;
}
if (ctl is ComboBox)
{
//(ctl as ComboBox).DropDownStyle = ComboBoxStyle.DropDownList;
}
if (ctl is DateTimePicker)
{
if (frmFont == EFormFont.BigFont)
{ (ctl as DateTimePicker).Size = new Size(190, 31); }
}
if (ctl is DataGridView)
{
DataGridView dgv = ctl as DataGridView;
//第一列如果为复选框,则设为可编辑
foreach (DataGridViewColumn column in dgv.Columns)
{
if (column.Index == 0 && column.CellTemplate is DataGridViewCheckBoxCell)
{ column.ReadOnly = false; }
else
{ column.ReadOnly = true; }
}
dgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;//列宽自动排列
dgv.RowHeadersVisible = false;
dgv.AllowUserToAddRows = false;
dgv.AllowUserToDeleteRows = false;
//dgv.AllowUserToResizeColumns = false;
dgv.AllowUserToResizeRows = false;
dgv.MultiSelect = false;
dgv.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dgv.AutoGenerateColumns = false;
dgv.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
dgv.RowsDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
dgv.RowsDefaultCellStyle.Font = new Font("宋体", 12, FontStyle.Bold);
dgv.RowTemplate.Height = 35;
dgv.CellClick += new DataGridViewCellEventHandler(dgvRoleList_CellContentClick);
dgv.DataBindingComplete += new DataGridViewBindingCompleteEventHandler(dgvSchoolList_DataBindingComplete);
//dgv.DataSourceChanged += new EventHandler(dataGridView_DataSourceChanged);
//dgv.CellValueChanged += new DataGridViewCellEventHandler(dataGridView_CellValueChanged);
}
if (frmFont == EFormFont.BigFont)
{
ctl.Font = new Font("宋体", 15.75F, FontStyle.Bold, GraphicsUnit.Point, ((byte)(134)));
}
if (ctl is Form || ctl is Panel || ctl is GroupBox || ctl is TabControl || ctl is TableLayoutPanel || ctl is FlowLayoutPanel)
{
MadeFormNew(ctl);
}
//ctl.ContextMenu = new ContextMenu();
}
}
/// <summary>
/// 定制菜单栏 -kkzy
/// </summary>
/// <param name="toolStripButtons"></param>
public static void MadeToolStripButtonStyle(ToolStrip toolStrip)
{
foreach (ToolStripItem vItem in toolStrip.Items)
{
if (vItem is ToolStripButton)
{
vItem.DisplayStyle = ToolStripItemDisplayStyle.ImageAndText;
vItem.ImageScaling = ToolStripItemImageScaling.None;
vItem.TextImageRelation = TextImageRelation.ImageAboveText;
}
}
}
#endregion
#region DataGridView 事件
/// <summary>
/// 列表点击记录选中行
/// </summary>
private static void dgvRoleList_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
try
{
if (e.RowIndex > -1 && e.ColumnIndex > -1)
{
DataGridView source = sender as DataGridView;
source.Tag = e.RowIndex;
}
}
catch (Exception ex)
{
LogHelper.Write("记录列表点击行出错: " + ex.Message, LogType.Exception);
}
}
/// <summary>
/// 列表重新绑定后将设置最后选中行
/// </summary>
private static void dgvSchoolList_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
try
{
if ((sender as DataGridView).Tag == null)
return;
DataGridView source = sender as DataGridView;
int lastSelectIndex = int.Parse((sender as DataGridView).Tag.ToString());
if (lastSelectIndex > -1)
source.Rows[lastSelectIndex].Selected = true;
}
catch (Exception ex)
{
LogHelper.Write("列表重新绑定后将设置最后选中行: " + ex.Message, LogType.Exception);
}
}
#endregion
#region DataGridView 底行合计数
/// <summary>
/// 计算合计算
/// </summary>
/// <param name="dgv">要计算的DataGridView</param>
private void SumDataGridView(DataGridView dgv)
{
if (dgv.DataSource == null) return;
DataTable dt = (DataTable)dgv.DataSource;
if (dt.Rows.Count < 1) return;
decimal[] tal = new decimal[dt.Columns.Count];
DataRow ndr = dt.NewRow();
string talc = "";
int number = 1;
foreach (DataRow dr in dt.Rows)
{
//dr["@xu.Hao"] = number++;
int n = 0;
foreach (DataColumn dc in dt.Columns)
{
if (talc == "" && dc.DataType.Name.ToUpper().IndexOf("STRING") >= 0) talc = dc.ColumnName;
if (dc.DataType.IsValueType)
{
string hej = dr[dc.ColumnName].ToString();
try
{
if (hej != string.Empty) tal[n] += decimal.Parse(hej);
}
catch (Exception) { }
}
n++;
}
}
ndr.BeginEdit();
for (int i = 0; i < dt.Columns.Count; i++)
{
if (tal[i] != 0)
ndr[i] = tal[i];
}
//ndr["@xu.Hao"] = ((int)(dt.Rows.Count + 1)).ToString();
if (talc != "") ndr[talc] = "[合计]";
ndr.EndEdit();
dt.Rows.Add(ndr);
dgv.Rows[dgv.Rows.Count - 1].DefaultCellStyle.BackColor = Color.FromArgb(255, 255, 210);
if (dgv.Tag == null)
{
foreach (DataGridViewColumn dgvc in dgv.Columns)
{
dgvc.SortMode = DataGridViewColumnSortMode.Programmatic;
}
}
dgv.Tag = ndr;
}
private void dataGridView_DataSourceChanged(object sender, EventArgs e)
{
DataGridView dgv = (DataGridView)sender;
DataTable dt = (DataTable)dgv.DataSource;
if (dt == null) return;
decimal[] tal = new decimal[dt.Columns.Count];
SumDataGridView(dgv);
}
private void dataGridView_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
DataGridView dgv = (DataGridView)sender;
if (dgv.Tag == null || e.RowIndex < 0 || e.RowIndex == dgv.Rows.Count - 1) return;
string col = dgv.Columns[e.ColumnIndex].DataPropertyName;
if (col == string.Empty) return;
if (((DataRowView)dgv.Rows[e.RowIndex].DataBoundItem).Row.Table.Columns[col].DataType.IsValueType)
{
decimal tal = 0;
foreach (DataGridViewRow dgvr in dgv.Rows)
{
if (dgvr.Index != dgv.Rows.Count - 1)
{
string hej = dgvr.Cells[e.ColumnIndex].Value.ToString();
if (hej != string.Empty) tal += decimal.Parse(hej);
}
}
if (tal == 0)
dgv[e.ColumnIndex, dgv.Rows.Count - 1].Value = DBNull.Value;
else
dgv[e.ColumnIndex, dgv.Rows.Count - 1].Value = tal;
}
}
#endregion 底行合计数
#region 定制控件样式
/// <summary>
/// 定制 DataGridView 样式
/// </summary>
/// <param name="dgv"></param>
public static void MadeDataGridView(DataGridView dgv)
{
foreach (DataGridViewColumn column in dgv.Columns)
{
if (column.Index == 0 && column.CellTemplate is DataGridViewCheckBoxCell)
{ column.ReadOnly = false; }
else
{ column.ReadOnly = true; }
}
dgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;//列宽自动排列
dgv.RowHeadersVisible = false;
dgv.AllowUserToAddRows = false;
dgv.AllowUserToDeleteRows = false;
//dgv.AllowUserToResizeColumns = false;
dgv.AllowUserToResizeRows = false;
dgv.MultiSelect = false;
dgv.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dgv.AutoGenerateColumns = false;
dgv.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
dgv.RowsDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
dgv.RowsDefaultCellStyle.Font = new Font("宋体", 12, FontStyle.Bold);
dgv.RowTemplate.Height = 35;
}
/// <summary>
/// 所有文本框不可编辑
/// </summary>
/// <param name="parentControl">父级容器</param>
/// <param name="textBoxs">TextBox[] 排除在父容器外</param>
public static void TextBoxEnable(Control parentControl, TextBox[] textBoxs)
{
foreach (Control ctl in parentControl.Controls)
{
if (ctl is TextBox)
{
bool IsExist = false;
foreach (TextBox textBox in textBoxs)
{
if (textBox.Name == (ctl as TextBox).Name)
{ IsExist = true; }
}
if (!IsExist)
{
TextBox txt = ctl as TextBox;
txt.ReadOnly = true;
txt.Cursor = Cursors.Hand;
txt.BackColor = Color.Gainsboro;
}
}
if (ctl is Form || ctl is Panel || ctl is GroupBox || ctl is TabControl || ctl is TableLayoutPanel || ctl is FlowLayoutPanel)
{ TextBoxEnable(ctl, textBoxs); }
}
}
/// <summary>
/// 所有文本框不可编辑
/// </summary>
/// <param name="parentControl">父级容器</param>
public static void TextBoxEnable(Control parentControl)
{
TextBoxEnable(parentControl, new TextBox[] { });
}
/// <summary>
/// 所有文本框不可编辑
/// </summary>
/// <param name="textBoxs">TextBox[]文本框</param>
public static void TextBoxEnable(TextBox[] textBoxs)
{
foreach (TextBox textBox in textBoxs)
{
textBox.ReadOnly = true;
textBox.Cursor = Cursors.Hand;
textBox.BackColor = Color.Gainsboro;
}
}
/// <summary>
/// 设置父级容器下的子控件的Enable属性
/// </summary>
/// <param name="parentControl">父级容器</param>
/// <param name="textIsRead">true表示可编辑</param>
public static void ControlsEnable(Control parentControl, bool Enable)
{
foreach (Control ctl in parentControl.Controls)
{
if (ctl is TextBox)
{
TextBox txt = ctl as TextBox;
txt.ReadOnly = !Enable;
txt.Cursor = Cursors.Hand;
if (!Enable)
{ txt.BackColor = Color.Gainsboro; }
else
{ txt.BackColor = Color.White; }
}
if (ctl is CheckBox)
{
(ctl as CheckBox).Enabled = Enable;
}
if (ctl is ComboBox)
{
(ctl as ComboBox).Enabled = Enable;
}
if (ctl is DateTimePicker)
{
(ctl as DateTimePicker).Enabled = Enable;
}
if (ctl is TabControl)
{
ControlsEnable((ctl as TabControl).SelectedTab, Enable);
}
if (ctl is Form || ctl is Panel || ctl is GroupBox || ctl is TableLayoutPanel || ctl is FlowLayoutPanel)
{
ControlsEnable(ctl, Enable);
}
}
}
#endregion
#region 控件初始化操作
/// <summary>
/// 遍历窗体,初始化控件
/// </summary>
/// <param name="parentControl">父级控件</param>
/// <param name="flag">是否清空DataGridView</param>
public static void ClearContrls(Control parentControl, Boolean flag)
{
foreach (Control ctl in parentControl.Controls)
{
if (ctl is TextBox)
{
TextBox textBox = (ctl as TextBox);
if (textBox.Tag != null && Convert.ToBoolean(textBox.Tag))
textBox.Text = GetStrMoney(0);
else
textBox.Text = string.Empty;
}
if (ctl is DateTimePicker)
{
//(ctl as DateTimePicker).Value = DateTime.Now;
}
if (ctl is ComboBox && (ctl as ComboBox).Items.Count > 0)
{
(ctl as ComboBox).SelectedIndex = 0;
}
if (ctl is CheckBox)
{
(ctl as CheckBox).Checked = false;
}
if (ctl is DataGridView && flag)
{
(ctl as DataGridView).DataSource = null;
}
if (ctl is TabControl)
{
ClearContrls((ctl as TabControl).SelectedTab, flag);
}
if (ctl is Form || ctl is Panel || ctl is GroupBox || ctl is TableLayoutPanel || ctl is FlowLayoutPanel)
{
ClearContrls(ctl, flag);
}
}
//Device.GetInstance().ledScreen.ShowHello();
}
/// <summary>
/// 遍历窗体,初始化控件
/// </summary>
/// <param name="parentControl">父级控件</param>
public static void ClearContrls(Control parentControl)
{
ClearContrls(parentControl, true);
}
/// <summary>
/// 下拉列表自适应内容宽度
/// </summary>
/// <param name="comboBox"></param>
public static void AdjustComboBoxDropDownListWidth(object comboBox)
{
Graphics g = null;
Font font = null;
try
{
ComboBox senderComboBox = null;
if (comboBox is ComboBox)
senderComboBox = (ComboBox)comboBox;
else if (comboBox is ToolStripComboBox)
senderComboBox = ((ToolStripComboBox)comboBox).ComboBox;
else
return;
int width = senderComboBox.Width;
g = senderComboBox.CreateGraphics();
font = senderComboBox.Font;
//checks if a scrollbar will be displayed.
//If yes, then get its width to adjust the size of the drop down list.
int vertScrollBarWidth =
(senderComboBox.Items.Count > senderComboBox.MaxDropDownItems)
? SystemInformation.VerticalScrollBarWidth : 0;
int newWidth;
foreach (object s in senderComboBox.Items) //Loop through list items and check size of each items.
{
if (s != null)
{
newWidth = (int)g.MeasureString(s.ToString().Trim(), font).Width
+ vertScrollBarWidth;
if (width < newWidth)
width = newWidth; //set the width of the drop down list to the width of the largest item.
}
}
senderComboBox.DropDownWidth = width;
}
catch
{ }
finally
{
if (g != null)
g.Dispose();
}
}
#endregion
#region 文本框长度验证
/// <summary>
/// 定制长度文本本框(限制输入长度并可选择是否允许输入特殊字符) -kkzy
/// </summary>
/// <param name="textBoxs">需要定制的文本框</param>
/// <param name="maxLength">文本框可输入的最大长度</param>
/// <param name="filterSpecial">是否可以输入特殊字符(true表示允许)</param>
/// <returns></returns>
public static void MadeLengthTextBox(TextBox[] textBoxs, int maxLength, bool filterSpecial)
{
foreach (TextBox lengthTextBox in textBoxs)
{
lengthTextBox.MaxLength = maxLength;
lengthTextBox.KeyPress += new KeyPressEventHandler(lengthTextBox_KeyPress);
if (!filterSpecial)
{
lengthTextBox.KeyPress += new KeyPressEventHandler(FilterSpecialTextBox_KeyPress);
}
}
}
//长度文本框按下事件(限制输入长度)
static void lengthTextBox_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar != '\b')
{
TextBox lengthTextBox = sender as TextBox;
byte[] b = Encoding.Default.GetBytes(lengthTextBox.Text.Trim() + e.KeyChar.ToString());
int m = b.Length;
if (m > lengthTextBox.MaxLength)
{
e.Handled = true;
}
}
}
#endregion
#region 文本框数字验证
/// <summary>
/// 定制数字文本框(只能输入数字并限制长度)
/// </summary>
/// <param name="textBoxs">需要定制的文本框</param>
/// <param name="maxLength">文本框可输入的最大长度</param>
/// <returns></returns>
public static void MadeDigitTextBox(TextBox[] textBoxs, int maxLength)
{
foreach (TextBox digitTextBox in textBoxs)
{
digitTextBox.MaxLength = maxLength;
digitTextBox.KeyPress += new KeyPressEventHandler(digitTextBox_KeyPress);
}
}
//数字文本框按下事件(限制输入非数字)
static void digitTextBox_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar != '\b')
{
//非数字
if (!char.IsDigit(e.KeyChar))
{
e.Handled = true;
}
}
}
#endregion
///////////////////////////////////////////
#region 文本框数字验证
/// <summary>
/// 定制数字文本框(只能输入数字并限制长度)
/// </summary>
/// <param name="textBoxs">需要定制的文本框</param>
/// <param name="maxLength">文本框可输入的最大长度</param>
/// <returns></returns>
public static void MadeDigitTextBoxStore(TextBox[] textBoxs, int maxLength)
{
foreach (TextBox digitTextBox in textBoxs)
{
digitTextBox.MaxLength = maxLength;
digitTextBox.KeyPress += new KeyPressEventHandler(digitTextBox_KeyPressStore);
}
}
//数字文本框按下事件(限制输入非数字)
static void digitTextBox_KeyPressStore(object sender, KeyPressEventArgs e)
{
if (e.KeyChar != '\b')
{
//非数字
//if (!char.IsDigit(e.KeyChar))
//{
// e.Handled = true;
//}
//if ((e.KeyChar < 48 || e.KeyChar > 57) && (e.KeyChar != 46) )
//if ((e.KeyChar >= '0' || e.KeyChar <= '9') && (e.KeyChar != 46) && (e.KeyChar >= 'a' && e.KeyChar <= 'z') && (e.KeyChar >= 'A' && e.KeyChar <= 'Z'))
if ((e.KeyChar >= '0' || e.KeyChar <= '9') && (e.KeyChar >= 'a' && e.KeyChar <= 'z') && (e.KeyChar >= 'A' && e.KeyChar <= 'Z'))
{
e.Handled = true;
}
}
}
#endregion
//////////////////////////////////////////
#region 金额文本框处理
/// <summary>
/// 金额文本框处理(只能输入数字并限制长度,文本框获取焦点后为数字表现形式,文本框焦点离开后为金额表现形式)
/// </summary>
/// <param name="textBoxs">需要定制的金额文本框</param>
/// <param name="maxLength">文本框可输入的最大长度</param>
public static void MadeMoneyTextBox(TextBox[] textBoxs, int maxLength)
{
foreach (TextBox moneyTextBox in textBoxs)
{
moneyTextBox.Text = "¥0.00";
moneyTextBox.MaxLength = maxLength;
moneyTextBox.Tag = true;
moneyTextBox.Enter += new EventHandler(moneyTextBox_Enter);
moneyTextBox.Leave += new EventHandler(moneyTextBox_Leave);
moneyTextBox.KeyPress += new KeyPressEventHandler(moneyTextBox_KeyPress);
}
}
/// <summary>
/// 金额文本框输入验证
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
static void moneyTextBox_KeyPress(object sender, KeyPressEventArgs e)
{
TextBox moneyTextBox = sender as TextBox;
try
{
if (e.KeyChar != '\b')
{
//非数字和非小数点
if (!char.IsDigit(e.KeyChar) && e.KeyChar != '.')
{
e.Handled = true;
}
//数字
if (char.IsDigit(e.KeyChar))
{
int pointIndex = moneyTextBox.Text.IndexOf('.');//获取小数点的索引
int charIndex = moneyTextBox.Text.LastIndexOf(e.KeyChar);
int slIndex = moneyTextBox.SelectionStart;
int lastIndex = moneyTextBox.Text.Length;
if (pointIndex > 0)
{
if (slIndex > pointIndex && lastIndex - pointIndex >= 3)
{
e.Handled = true;
}
}
else if (pointIndex == 0)
{
if (lastIndex == 3)
{
e.Handled = true;
}
}
//if (pointIndex&& slIndex - pointIndex > 2)
//{ e.Handled = true; }
}
//小数点
if (e.KeyChar == '.')
{
int count = 0;//记录小数点位数
foreach (char c in moneyTextBox.Text)//获取小数点位数
{ if (c == '.') count++; }
if (count > 0 || moneyTextBox.Text.Length == 0)//只允输入一个小数点
{ e.Handled = true; }
}
}
}
catch { moneyTextBox.Text = GetStrMoney(0); }
}
/// <summary>
/// 金额文本框进入事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
static void moneyTextBox_Enter(object sender, EventArgs e)
{
if (sender is TextBox)
{
TextBox moneyTextBox = (TextBox)sender;
moneyTextBox.Text = GetDcmMoney(moneyTextBox.Text).ToString();
}
}
/// <summary>
/// 金额文本框离开事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
static void moneyTextBox_Leave(object sender, EventArgs e)
{
TextBox moneyTextBox = (TextBox)sender;
try
{
if (sender is TextBox)
{
decimal flag = 0M;
if (!decimal.TryParse(moneyTextBox.Text.Trim(), out flag))
{
moneyTextBox.Text = "0";
}
if (moneyTextBox.Text.Trim() == string.Empty || moneyTextBox.Text.Trim() == "." || moneyTextBox.Text == "0.")
{
moneyTextBox.Text = "0";
}
moneyTextBox.Text = GetStrMoney(Convert.ToDecimal(moneyTextBox.Text));
}
}
catch { moneyTextBox.Text = GetStrMoney(0); }
}
#endregion
#region 文本框输入验证
/// <summary>
/// 定制文本框输入(禁止非字母和数字输入) -kkzy
/// </summary>
/// <param name="textBoxs">需要定制的文本框</param>
/// <param name="maxLength">文本框可输入的最大长度</param>
/// <returns></returns>
public static void MadeDigitAndWordsTextBox(TextBox[] textBoxs, int maxLength)
{
foreach (TextBox digitAndWordsTextBox in textBoxs)
{
digitAndWordsTextBox.MaxLength = maxLength;
digitAndWordsTextBox.KeyPress += new KeyPressEventHandler(DigitAndWordsTextBox_KeyPress); ;
}
}
//文本框限制输入事件(禁止非字母和数字输入)
static void DigitAndWordsTextBox_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar != '\b')
{
if (!char.IsLetterOrDigit(e.KeyChar))
{
e.Handled = true;
}
}
}
//文本框限制输入事件(禁止输入特殊字符) -kkzy
static void FilterSpecialTextBox_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar != '\b')
{
//Regex regExp = new Regex("[~!@#$%^&*()=+[\\]{}''\";:/?.,><`|!·¥…—()\\-、;:。,》《]");
Regex regExp = new Regex("[~!@#$%^&*=+[\\]{}''\";:/?><`|!¥…—\\-、;]");
if (regExp.IsMatch(e.KeyChar.ToString()))
{
e.Handled = true;
}
}
}
#endregion
#region Form 业务处理
/// <summary>
/// 金额处理..(返回 "¥ 1,000.00" 表现形式)
/// </summary>
/// <param name="money">decimal类型金额</param>
/// <returns></returns>
public static string GetStrMoney(decimal money)
{
try
{
string strMoney = money.ToString();
if (money == 0)
{
return "¥0.00";
}
if (strMoney.Contains("."))
{
string tempMoney = strMoney.Substring(0, strMoney.IndexOf("."));
if (tempMoney.Length > 3)
{
strMoney = strMoney.Insert(tempMoney.Length - 3, ",");
}
string tempMoney2 = strMoney.Substring(strMoney.IndexOf("."));
if (tempMoney2.Length > 3)
{
strMoney = strMoney.Remove(strMoney.IndexOf(".") + 3);
}
}
else
{
if (strMoney.Length > 3)
{
strMoney = strMoney.Insert(strMoney.Length - 3, ",") + ".00";
}
else
{
strMoney = strMoney + ".00";
}
}
while (strMoney.Contains(","))
{
string tempMoney = strMoney.Substring(0, strMoney.IndexOf(","));
if (tempMoney.Length > 3)
{
strMoney = strMoney.Insert(tempMoney.Length - 3, ",");
}
else
break;
}
return "¥" + strMoney;
}
catch { return "¥ 0.00"; }
}
/// <summary>
/// 金额处理..(返回 "1000" 表现形式)
/// </summary>
/// <param name="strMoney">字符类型金额</param>
/// <returns></returns>
public static decimal GetDcmMoney(string strMoney)
{
try
{
if (strMoney == string.Empty || strMoney == "." || strMoney == "0.")
{
return 0;
}
for (int i = 0; i < strMoney.Length; i++)
{
if (strMoney[i] == '¥' || strMoney[i] == ',')
{
strMoney = strMoney.Remove(i, 1);
}
if (strMoney[i] == '.' && strMoney.Substring(i + 1) != string.Empty && Convert.ToInt32(strMoney.Substring(i + 1)) == 0)
{
strMoney = strMoney.Remove(i);
}
}
return Convert.ToDecimal(strMoney);
}
catch { return 0; }
}
/// <summary>
/// 处理模块名称,剔除快捷键
/// </summary>
/// <param name="modelName"></param>
/// <returns></returns>
public static string GetModelName(string modelName)
{
if (modelName == string.Empty)
{ return string.Empty; }
//查找括号
int index = modelName.IndexOf('(');
if (index < 0)
{ return modelName; }
return modelName.Substring(0, index);
}
/// <summary>
/// 获取时间差
/// </summary>
/// <param name="Interval"></param>
/// <param name="StartDate"></param>
/// <param name="EndDate"></param>
/// <returns></returns>
public static long DateDiff(DateInterval Interval, DateTime StartDate, DateTime EndDate)
{
long lngDateDiffValue = 0;
System.TimeSpan TS = new System.TimeSpan(EndDate.Ticks - StartDate.Ticks);
switch (Interval)
{
case DateInterval.Second:
lngDateDiffValue = (long)TS.TotalSeconds;
break;
case DateInterval.Minute:
lngDateDiffValue = (long)TS.TotalMinutes;
break;
case DateInterval.Hour:
lngDateDiffValue = (long)TS.TotalHours;
break;
case DateInterval.Day:
lngDateDiffValue = (long)TS.Days;
break;
case DateInterval.Week:
lngDateDiffValue = (long)(TS.Days / 7);
break;
case DateInterval.Month:
lngDateDiffValue = (long)(TS.Days / 30);
break;
case DateInterval.Quarter:
lngDateDiffValue = (long)((TS.Days / 30) / 3);
break;
case DateInterval.Year:
lngDateDiffValue = (long)(TS.Days / 365);
break;
}
return (lngDateDiffValue);
}
#endregion
#region 定制文本框可随便输入字符串
/// <summary>
/// 定制文本框可随便输入字符串
/// </summary>
/// <param name="textBoxs"></param>
/// <param name="maxLength"></param>
public static void MadeStringTextBox(TextBox[] textBoxs, int maxLength)
{
foreach (TextBox digitTextBox in textBoxs)
{
digitTextBox.MaxLength = maxLength;
digitTextBox.KeyPress += new KeyPressEventHandler(stringTextBox_KeyPress);
}
}
//字符串输入无限制
static void stringTextBox_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar != '\b')
{
//非数字
if (!char.IsDigit(e.KeyChar))
{
e.Handled = false;
}
}
}
#endregion
#region 文本框数字验证
/// <summary>
/// 定制数字下拉框(只能输入数字并限制长度)
/// </summary>
/// <param name="textBoxs">需要定制的下拉框</param>
/// <param name="maxLength">下拉框可输入的最大长度</param>
/// <returns></returns>
public static void MadeDigitComboBox(ComboBox[] cmbBoxs, int maxLength)
{
foreach (ComboBox digitTextBox in cmbBoxs)
{
digitTextBox.MaxLength = maxLength;
digitTextBox.KeyPress += new KeyPressEventHandler(digitComboBox_KeyPress);
}
}
//数字文本框按下事件(限制输入非数字)
static void digitComboBox_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar != '\b')
{
////非数字
//if (!char.IsDigit(e.KeyChar))
//{
// e.Handled = true;
//}
if ((e.KeyChar < 48 || e.KeyChar > 57) && (e.KeyChar != 46))
{
e.Handled = true;
}
}
}
#endregion
#region 文本框输入验证
/// <summary>
/// 定制文本框输入(禁止非字母和数字输入) -kkzy
/// </summary>
/// <param name="textBoxs">需要定制的文本框</param>
/// <param name="maxLength">文本框可输入的最大长度</param>
/// <returns></returns>
public static void MadeDigitAndWordsTextBoxNew(TextBox[] textBoxs, int maxLength)
{
foreach (TextBox digitAndWordsTextBox in textBoxs)
{
digitAndWordsTextBox.MaxLength = maxLength;
digitAndWordsTextBox.KeyPress += new KeyPressEventHandler(DigitAndWordsTextBox_KeyPressNew); ;
}
}
//文本框限制输入事件(禁止非字母和数字输入)
static void DigitAndWordsTextBox_KeyPressNew(object sender, KeyPressEventArgs e)
{
if (e.KeyChar != '\b')
{
//if (!char.IsLetterOrDigit(e.KeyChar))
//{
// e.Handled = true;
//}
if ((e.KeyChar < 48 || e.KeyChar > 57) && (e.KeyChar != 46))
{
e.Handled = true;
}
}
}
#endregion
#region 文本框数字验证
/// <summary>
/// 定制数字文本框(只能输入数字并限制长度)
/// </summary>
/// <param name="textBoxs">需要定制的文本框</param>
/// <param name="maxLength">文本框可输入的最大长度</param>
/// <returns></returns>
public static void MadeDigitTextBoxNew(TextBox[] textBoxs, int maxLength)
{
foreach (TextBox digitTextBox in textBoxs)
{
digitTextBox.MaxLength = maxLength;
digitTextBox.KeyPress += new KeyPressEventHandler(digitTextBox_KeyPressNew);
}
}
//数字文本框按下事件(限制输入非数字)
static void digitTextBox_KeyPressNew(object sender, KeyPressEventArgs e)
{
if (e.KeyChar != '\b')
{
//if (!char.IsLetterOrDigit(e.KeyChar))
//{
// e.Handled = true;
//}
if ((e.KeyChar < 48 || e.KeyChar > 57) && (e.KeyChar != 46))
{
e.Handled = true;
}
}
}
#endregion
#region 文本框数字验证
/// <summary>
/// 定制数字下拉框(只能输入数字并限制长度)
/// </summary>
/// <param name="textBoxs">需要定制的下拉框</param>
/// <param name="maxLength">下拉框可输入的最大长度</param>
/// <returns></returns>
public static void MadeDigitComboBoxNumeric(ComboBox[] cmbBoxs, int maxLength)
{
foreach (ComboBox digitTextBox in cmbBoxs)
{
digitTextBox.MaxLength = maxLength;
digitTextBox.KeyPress += new KeyPressEventHandler(digitComboBoxNumeric_KeyPress);
}
}
//数字文本框按下事件(限制输入非数字)
static void digitComboBoxNumeric_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar != '\b')
{
////非数字
//if (!char.IsDigit(e.KeyChar))
//{
// e.Handled = true;
//}
if ((e.KeyChar < 48 || e.KeyChar > 57) && (e.KeyChar != 46))
{
e.Handled = true;////-?(\d{1,8}(\.\d{1,4})?)
}
}
}
#endregion
///<summary>
/// 判断输入的字符串只包含数字,可以匹配整数和浮点数
/// </summary>
public static bool IsNumber(string input)
{
string pattern = @"^(?:(?:[1-9]|[1-8][0-9])(\.)?(?(1)[0-9]{0,8})|90|0\.[0-9]{1,8})$";
Regex regex = new Regex(pattern);
return regex.IsMatch(input);
}
/// <summary>
/// 判断字符串中中的点
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static bool whiterString(string str)
{
string a = str.Substring(0, 1);
string b = str.Substring(str.Length - 1, 1);
string[] num = str.Split('.');
if (a.Equals(".") || b.Equals(".") || num.Length > 1)
{
return false;
}
else
return true;
}
#region 文本框空格验证
/// <summary>
/// 定制TEXT文本框(不允许输入空格)
/// </summary>
/// <param name="textBoxs">需要定制的文本框</param>
/// <returns></returns>
public static void MadeDigitTextBoxSpacebar(TextBox[] textBoxs)
{
foreach (TextBox digitTextBox in textBoxs)
{
digitTextBox.KeyPress += new KeyPressEventHandler(digitTextBoxSpacebar_KeyPress);
}
}
//数字文本框按下事件(限制输入非数字)
static void digitTextBoxSpacebar_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == 32)//&& !Char.IsDigit(e.KeyChar) e.KeyChar != '\b' &&
{
e.Handled = true;
}
#endregion
}
}