C# 定义用户控件并添加属性(制作一个限定输入的文本框)

   用用户控件是我们常用的,刚搞了这方面,也记录一下。

   这里做了一个限定输入与提示的文本框:

   1.第一步:新建一个控件库项目或者直接在建好的项目右键添加:用户控件

   

 2.第二步:从工具箱里面拖动一个文本框,然后写代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace ControlText1
{
[ToolboxBitmap(@"E/Images/Logo.Icon")] //添加图标
public partial class UserControl1 : UserControl
{
public UserControl1()
{
InitializeComponent();
}
//添加最小值属性
protected int _userControlMinLenght1;

public int UserControlMinLenght1
{
get { return _userControlMinLenght1; }
set
{
if (value > 0)
{
this.txtTest.MaxLength = value;
this._userControlMinLenght1 = value;
}
else
{
_userControlMinLenght1 = 0;
}
}
}
//添加最大值属性
protected int _userControlMaxLenght1;

public int UserControlMaxLenght1
{
get { return _userControlMaxLenght1; }
set
{
if (value > 0)
{
this.txtTest.MaxLength = value;
this._userControlMaxLenght1 = value;
}
else
{
_userControlMaxLenght1 = 10;
}
}
}

/// <summary>
/// 该控件停止操作时发生
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void txtTest_Leave(object sender, EventArgs e)
{
try
{

int a = Convert.ToInt32(txtTest.Text);
//文本框的最大值与最小值限定
if (a < _userControlMinLenght1 || a > _userControlMaxLenght1)
{
txtTest.Text = "输入有误";
txtTest.Font = new System.Drawing.Font(Font.FontFamily, 11, FontStyle.Italic);
txtTest.BackColor = ColorTranslator.FromHtml("#f7e7e7");
}
}
catch (Exception)
{
txtTest.Text = "输入有误";
txtTest.Font = new System.Drawing.Font(Font.FontFamily, 11, FontStyle.Italic);
txtTest.BackColor = Color.Gray;
}
}
/// <summary>
/// 鼠标按下发生
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void txtTest_MouseDown(object sender, MouseEventArgs e)
{
txtTest.Text = null;
txtTest.BackColor = Color.White;
}
}
}

3.收工测试,(没问题)
这样为控件添加了两个属性:最大值与最小值,这么文本框用起来就方便多了。

posted @ 2012-02-22 23:16  garyChong  阅读(1984)  评论(0编辑  收藏  举报