如何在C#中根据已有的控件(比如TextBox),派生出一个自定义控件?最好附上例子,新手。。。

 我来答
zhugezhiyuan
2011-11-05 · TA获得超过169个赞
知道小有建树答主
回答量:150
采纳率:0%
帮助的人:131万
展开全部
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel;
using System.Drawing;
using System.Collections;

namespace FumaCRM_BS.WebControls
{
/// <summary>
/// 普通文本框封装
/// </summary>
[ToolboxData("<{0}:FBSTextBox runat=server></{0}:FBSTextBox>"), DefaultProperty("ValidType")]
public class FBSTextBox : System.Web.UI.WebControls.TextBox, INamingContainer
{
/// <summary>
/// 构造函数,初始化部分属性
/// </summary>
public FBSTextBox()
{
clearText = false;
decimalDigits = 2;
gotfocusColor = Color.FromArgb(255, 255, 192);
jsSrc = "../Resource/Js/checkvalid.js";
}

#region Fields
private string errorMessage;
private string validRegularExpression;
private AvailableType validType;
private bool clearText;
private Color gotfocusColor;
private Color lostfocusColor;
private RestrictType restType;
private int decimalDigits;
private string jsSrc;
private string buttonId;

#endregion

#region Properties

[Category("Appearance"), Browsable(true), Description("错误信息")]
public string ErrorMessage
{
get
{
return errorMessage;
}
set
{
errorMessage = value;
}
}

[Category("Appearance"), Browsable(true), Description("自定义正则表达式")]
public string ValidRegularExpression
{
get
{
return validRegularExpression;
}
set
{
validRegularExpression = value;
}
}

[Category("Appearance"), Browsable(true), Description("验证类型")]
public AvailableType ValidType
{
get
{
return validType;
}
set
{
validType = value;
}
}

[Category("Appearance"), Browsable(true), Description("是否清空错误的数据")]
public bool ClearText
{
get
{
return clearText;
}
set
{
clearText = value;
}
}

[Category("Appearance"), DefaultValue("White"), Bindable(true), Description("获得焦点时的颜色")]
public Color GotfocusColor
{
get
{
return gotfocusColor;
}
set
{
gotfocusColor = value;
}
}

[Category("Appearance"), DefaultValue("White"), Bindable(true), Description("失去焦点时的颜色")]
public Color LostfocusColor
{
get
{
return lostfocusColor;
}
set
{
lostfocusColor = value;
}
}

[Category("Appearance"), Browsable(true), Description("限制输入类型")]
public RestrictType RestType
{
get
{
return restType;
}
set
{
restType = value;
}
}

[Category("Appearance"), DefaultValue("2"), Bindable(false), Description("限制输入浮点数小数位数")]
public int DecimalDigits
{
get
{
return decimalDigits;
}
set
{
decimalDigits = value;
}
}

[Category("Appearance"), Bindable(false), Description("JS脚本相对路径")]
public string JsSrc
{
get
{
return jsSrc;
}
set
{
jsSrc = value;
}
}

[Category("Appearance"), Bindable(false), Description("回车触发Click事件的ButtonID")]
public string ButtonID
{
get
{
return buttonId;
}
set
{
buttonId = value;
}
}

#endregion

#region CreateControl

protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);

ClientScriptManager client = Page.ClientScript;

#region 注册js脚本

if (!client.IsClientScriptBlockRegistered("checkvalid"))
{
if (jsSrc == null || jsSrc == "")
jsSrc = "../Resource/Js/checkvalid.js";
client.RegisterStartupScript(this.GetType(), "checkvalid", "<script language=\"javascript\" src=\"" + jsSrc + "\"></script>");
}

#endregion

#region 获得/失去焦点改变背景颜色

base.Attributes.Add("onBlur", "changeColor('" + ClientID + "', '" + Color2WebColorString(lostfocusColor) + "');");
base.Attributes.Add("onfocus", "changeColor('" + ClientID + "', '" + Color2WebColorString(gotfocusColor) + "');");

if (buttonId != null && buttonId != string.Empty)
{
base.Attributes.Add("onkeydown", "keydown('" + buttonId + "');");
}
else
{
base.Attributes.Add("onkeydown", "nokeydown();");
}

#endregion

if (ValidType != AvailableType.NoSet)
{
string regExp = GetRegularExpressions(ValidType);
base.Attributes.Add("onBlur", "isValid('" + ClientID + "','" + regExp + "','" + Color2WebColorString(lostfocusColor) + "','" + errorMessage + "','" + clearText + "');");
}

if (validRegularExpression != null && validRegularExpression.Trim() != string.Empty)
{
string regExp = validRegularExpression;
base.Attributes.Add("onBlur", "isValid('" + ClientID + "','" + regExp + "','" + Color2WebColorString(lostfocusColor) + "','" + errorMessage + "','" + clearText + "');");
}

if (RestType != RestrictType.NoSet)
{
string regExp = GetRegularExpressions(RestType);
base.Attributes.Add("onkeyup", "restrictedInput('" + ClientID + "','" + regExp + "');");
}
}

#endregion

#region Enums

/// <summary>
/// 校验类型
/// </summary>
public enum AvailableType
{
NoSet = 0,
Int = 1,
PositiveInt = 2,
NegativeInt = 3,
NonNegativeInt = 4,
NonPositiveInt = 5,
RegularExpression = 6,
Float = 7,
PositiveFloat = 8,
NegativeFloat = 9,
NonNegativeFloat = 10,
NonPositiveFloat = 11,
Email = 12,
Url = 13,
Money = 14
}

/// <summary>
/// 限制输入类型
/// </summary>
public enum RestrictType
{
NoSet = 0,
Letter = 1,
SmallLetter = 2,
CapitalLetter = 3,
Int = 4,
Float = 5,
}

#endregion

#region Private Functions

private string GetRegularExpressions(RestrictType restType)
{
switch (restType)
{
case RestrictType.Letter:
return @"^[A-Za-z]+$";
case RestrictType.CapitalLetter:
return @"^[A-Z]+$";
case RestrictType.SmallLetter:
return @"^[a-z]+$";
case RestrictType.Int:
return @"^[0-9]*[0-9][0-9]*$";
case RestrictType.Float:
if (decimalDigits == 0)
return @"^\d*\.?\d{0,}$";
else
return @"^\d*\.?\d{0," + decimalDigits + "}$";
default:
return "";
}
}

private string GetRegularExpressions(AvailableType avilType)
{
switch (avilType)
{
case AvailableType.Int://整数
return @"^-?\\d+$";

case AvailableType.PositiveInt://正整数
return @"^[0-9]*[1-9][0-9]*$";

case AvailableType.NegativeInt://负整数
return @"^-[0-9]*[1-9][0-9]*$";

case AvailableType.NonNegativeInt://非负整数
return @"^\\d+$";

case AvailableType.NonPositiveInt://非正整数
return @"^((-\\d+)|(0+))$";

case AvailableType.Float://浮点数
return @"^(-?\\d+)(\\.\\d+)?$";

case AvailableType.PositiveFloat://正浮点
return @"^(([0-9]+\\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\\.[0-9]+)|([0-9]*[1-9][0-9]*))$";

case AvailableType.NegativeFloat://负浮点
return @"^(-(([0-9]+\\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\\.[0-9]+)|([0-9]*[1-9][0-9]*)))$";

case AvailableType.NonNegativeFloat://非正浮点
return @"^\\d+(\\.\\d+)?$";

case AvailableType.NonPositiveFloat://非负浮点
return @"^((-\\d+(\\.\\d+)?)|(0+(\\.0+)?))$";

case AvailableType.Email://E-mail
return @"^[\\w-]+(\\.[\\w-]+)*@[\\w-]+(\\.[\\w-]+)+$";

case AvailableType.Url://Url
return @"^[a-zA-z]+://(\\w+(-\\w+)*)(\\.(\\w+(-\\w+)*))*(\\?\\S*)?$";

case AvailableType.Money://Money
return @"^(\\d+|[1-9])(\\.\\d{0,2})?$";
default:
return "";
}
}

/// <summary>
/// 颜色转换函数
/// </summary>
/// <param name="c"></param>
/// <returns></returns>
private string Color2WebColorString(Color c)
{
WebColorConverter wcc = new WebColorConverter();
return wcc.ConvertToString(c);
}

#endregion
}
}
百度网友9976b697e
2011-11-05
知道答主
回答量:19
采纳率:0%
帮助的人:5.2万
展开全部
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.ComponentModel;

namespace WebSerTest
{
class gxRichTextBox : System.Windows.Forms.RichTextBox
{
private delegate void ReadFileOneByOne(string FilePath);
public gxRichTextBox()
{
this.AllowDrop = true;//接受拖拽
this.AcceptsTab = true;//接受TAB键
this.DragDrop += new System.Windows.Forms.DragEventHandler(gxRichTextBox_DragDrop);
this.DragEnter += new System.Windows.Forms.DragEventHandler(gxRichTextBox_DragEnter);
}

private string _gxFilter = "txt,sql,asm";
[Description("可以打开的文件类型,以 ,分割开")]
public string GxFilter
{
get { return _gxFilter; }
set { _gxFilter = value; }
}

private int _gxBuffer;
[Description("每次读取的文件流的大小")]
public int GxBuffer
{
get { return _gxBuffer; }
set { _gxBuffer = value; }
}

private long _gxFileLength;
[Description("文件的总大小")]
public long GxFileLenght
{
get { return _gxFileLength; }
set { _gxFileLength = value; }
}

private int _gxStep;
[Description("读取文件的进度")]
public int GxStep
{
get { return _gxStep; }
set { _gxStep = value; }
}

private bool Busy =false;

void gxRichTextBox_DragEnter(object sender, System.Windows.Forms.DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}

void gxRichTextBox_DragDrop(object sender, System.Windows.Forms.DragEventArgs e)
{
string filepath = ((string[])e.Data.GetData(DataFormats.FileDrop))[0].ToString();
ReadFileOneByOne rf = new ReadFileOneByOne(ReadFile);
rf.BeginInvoke(filepath, null, null);
}

void ReadFile(string filepath)
{
if (Busy) return;
byte[] buffer = new byte[_gxBuffer];//每次读取多少
long f_len = 0; //文件流的当前位置
string fileExt = System.IO.Path.GetExtension(filepath).ToUpper();//文件类型
foreach (string str in _gxFilter.ToUpper().Split(','))
{
if (fileExt == "." + str)
{
System.IO.FileStream fl = null;
try
{
fl = new System.IO.FileStream(filepath, System.IO.FileMode.Open);
_gxFileLength = fl.Length;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
this.Text = string.Empty;
int effect = 0;//校验文件是否读取完毕的状态

do
{
Busy = true;
effect = fl.Read(buffer, 0, buffer.Length);//循环读取文件
if (effect != buffer.Length)
{
break;
}
f_len += effect; //累加校验和
_gxStep += 1;
this.AppendText(Encoding.Default.GetString(buffer));//边读边显示
fl.Seek(f_len, System.IO.SeekOrigin.Begin);//设置读取指针的当前位置
} while (true);
byte[] lastbuffer = new byte[fl.Length -f_len];
fl.Seek(f_len, System.IO.SeekOrigin.Begin);//设置读取指针的当前位置
fl.Read(lastbuffer, 0, lastbuffer.Length); //截取最后没有读取的部分
_gxStep += 1;
this.AppendText(Encoding.Default.GetString(lastbuffer));//显示最后一部分
Busy = false;
fl.Close();
fl.Dispose();
MessageBox.Show("读取完毕!");
_gxStep = 0;
}
}

}
}
}
新建一个CS文件 清空后 把这段代码贴进去 就可以看到效果了 这个列子主要是打开大文件,比如 4M的txt 用记事本肯定很慢 这个就好点!
本回答被提问者采纳
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
死死死死鱼眼Y
2011-11-05
知道答主
回答量:7
采纳率:0%
帮助的人:3.8万
展开全部
神奇一

   挥一挥手,新衣服即刻穿上身

   昨天,当记者来到麦德信息科技有限公司时,一进门,就看到一女生正在“镜子”前“试穿”衣服。只见她站在离镜子约1米处,双手上下挥动,“镜子”里的她就穿上了她要想试穿的衣服。

   带着好奇心,记者也来到了这块神奇的“镜子”面前,记者发现,这面镜子的右上方有4个按钮,分别是“保存”,“箭头”、“男装”、“女装”按钮。同时,记者还发现,镜子中的自己在手部分别有“红”、“绿”两个点。这两个点会随着记者手部的移动而移动。随后,记者按照工作人员的指示,点击右上角的按钮,选择了想要试穿的衣服,当记者挥动手臂,确认选择衣服后,该衣服就真的“穿”在了记者的身上,并且还随着记者身体的晃动而晃动。
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
endall_man
2011-11-05 · TA获得超过154个赞
知道小有建树答主
回答量:173
采纳率:0%
帮助的人:112万
展开全部
一个比较简单的方法,就是直接继承该控件
public class NewTextBox:TextBox
{
.....根据需求编写实际内容.....
}
New
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
收起 更多回答(2)
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式