using System.Drawing;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
namespace Dongke.WinForm.Controls
{
///
/// 编号输入文本框(数字、字母和特殊字符)
///
[ToolboxBitmap(typeof(TextBox))]
public class TxtCodeNo : TextBoxCodeBase
{
#region 常量
private static string CODE_NO_REGULAR = @"^(?:[\D]*|[\S\s]*[\D]+)(?[\d]+)(?:[\D]*)$";
#endregion
#region 构造函数
///
/// 编号输入文本框(数字、字母和特殊字符)
///
public TxtCodeNo()
{
this.Regular = this.GetCodeRegular();
}
#endregion
#region 保护方法
///
/// 获取编号正则表达式
///
///
protected virtual string GetCodeRegular()
{
return CODE_NO_REGULAR;
}
#endregion
#region 公有方法
///
/// 获取下一个编号
///
/// 增加量
/// 数值超长后是否截断
/// 新编号
public string GetNextCodeNo(int value = 1, bool clip = false)
{
string codeFormat = null;
decimal number = 0;
int length = 0;
if (this.GetMatchCodeNo(out codeFormat, out number, out length))
{
return this.GetNextCodeNo(codeFormat, number + value, length, clip);
}
return null;
}
#endregion
#region 私有方法
///
/// 获取条码格式
///
/// 编号格式化
/// 数值部分
/// 数值部分长度
/// 条码格式是否正确
private bool GetMatchCodeNo(out string codeFormat, out decimal number, out int length)
{
return TxtCodeNo.GetMatchCodeNo(this.Text, this.Regular, out codeFormat, out number, out length);
}
///
/// 获取下一个编号
///
/// 编号格式化
/// 数值部分
/// 数值部分长度
/// 数值超长后是否截断
/// 新编号
private string GetNextCodeNo(string codeFormat, decimal number, int length, bool clip = false)
{
string no = number.ToString(string.Empty.PadLeft(length, Constant.C_0));
if (clip && no.Length > length)
{
no = no.Substring(no.Length - length, length);
}
return string.Format(codeFormat, no);
}
#endregion
#region 静态方法
///
/// 获取编号格式
///
/// 编号
/// 编号正则表达式
/// 编号格式化
/// 数值部分
/// 数值部分长度
/// 编号格式是否正确
private static bool GetMatchCodeNo(string codeNo, string codeRegular,
out string codeFormat, out decimal number, out int length)
{
codeFormat = codeNo;
number = 0;
length = 0;
bool result = false;
if (string.IsNullOrWhiteSpace(codeNo) ||
string.IsNullOrWhiteSpace(codeRegular) ||
!codeRegular.Contains("?"))
{
return result;
}
Match match = Regex.Match(codeNo, codeRegular);
if (match.Success)
{
StringBuilder sb = new StringBuilder();
Group noGroup = match.Groups["no"];
if (noGroup.Success)
{
string no = noGroup.Value;
if (decimal.TryParse(no, out number))
{
result = true;
int index = noGroup.Index;
length = noGroup.Length;
sb.Append(codeNo.Substring(0, index));
sb.Append("{0}");
sb.Append(codeNo.Substring(index + length));
codeFormat = sb.ToString();
}
}
}
return result;
}
#endregion
}
}