zoukankan      html  css  js  c++  java
  • 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.收工测试,(没问题)
    这样为控件添加了两个属性:最大值与最小值,这么文本框用起来就方便多了。

  • 相关阅读:
    快过年了,博客园里的文章也变少了
    IP格式检查、IP INT 转换
    ip地址与数字相互转换的sql函数 [ZT]
    SQL Server 2005 TSQL的增強功能 [ZT]
    清除某个数据库的所有数据库连接的存储过程 [ZT]
    C# 3.0新特性
    C#中的委托和事件 [ZT]
    C# 各种进制之间相互转换 [ZT]
    升级到Visual Studio 2008的10个技巧[转]
    ASP.NET备份恢复SqlServer数据库 [ZT]
  • 原文地址:https://www.cnblogs.com/graypigeon/p/2364022.html
Copyright © 2011-2022 走看看