本帖最后由 paschen 于 2011-02-20 18:39:06 编辑

解决方案 »

  1.   

    将它设置为 DataGridViewNumberBoxCell类型,写个方法。
     public class DataGridViewNumberBoxCell : DataGridViewTextBoxCell
            {
                private int m_decimalLength = 0;
                private decimal m_maxValue = 0;
                private string m_formatString = "#,##0";
                private static Type defaultEditType = typeof(dgvNumControl);
                private static Type defaultValueType = typeof(System.Decimal);            [DefaultValue(0)]
                public int DecimalLength
                {
                    get { return m_decimalLength; }
                    set
                    {
                        if (m_decimalLength != value)
                        {
                            SetDecimalLength(this.RowIndex, value);
                            OnCommonChange();  // Assure that the cell/column gets repainted and autosized if needed
                        }
                    }
                }            [DefaultValue(0)]
                public decimal MaxValue
                {
                    get { return m_maxValue; }
                    set
                    {
                        if (m_maxValue != value)
                        {
                            SetMaxValue(this.RowIndex, value);
                            OnCommonChange();  // Assure that the cell/column gets repainted and autosized if needed
                        }
                    }
                }            public string FormatString
                {
                    get { return m_formatString; }
                    set
                    {
                        if (m_formatString != value)
                        {
                            SetFormatString(this.RowIndex, value);
                            //OnCommonChange();  // Assure that the cell/column gets repainted and autosized if needed
                        }
                    }
                }            protected override void OnEnter(int rowIndex, bool throughMouseClick)
                {
                    base.OnEnter(rowIndex, throughMouseClick);
                }            /// <summary>
                /// 
                /// </summary>
                public DataGridViewNumberBoxCell()
                {
                    //this.Value = 0;
                    //LibFunc.ToDecimal(this.Value).ToString("#,##0");
                    //this.Style.Format = "#,##0";
                    this.Style.Alignment = DataGridViewContentAlignment.MiddleRight;
                }            public override object Clone()
                {
                    DataGridViewNumberBoxCell dataGridViewCell = base.Clone() as DataGridViewNumberBoxCell;
                    if (dataGridViewCell != null)
                    {
                        dataGridViewCell.DecimalLength = this.DecimalLength;
                        dataGridViewCell.MaxValue = this.MaxValue;
                        dataGridViewCell.FormatString = this.FormatString;
                    }
                    return dataGridViewCell;
                }            internal void SetDecimalLength(int rowIndex, int value)
                {
                    m_decimalLength = value;
                    if (OwnsEditingControl(rowIndex))
                    {
                        this.EditingTNumEditBox.DecimalLength = value;
                    }
                }            internal void SetMaxValue(int rowIndex, decimal value)
                {
                    m_maxValue = value;
                    if (OwnsEditingControl(rowIndex))
                    {
                        this.EditingTNumEditBox.MaxValue = value;
                    }
                }            internal void SetFormatString(int rowIndex, string value)
                {
                    m_formatString = value;
                    //if (OwnsEditingControl(rowIndex))
                    //{
                    //    this.EditingTNumEditBox.FromatString = value;
                    //}
                }            private dgvNumControl EditingTNumEditBox
                {
                    get
                    {
                        return this.DataGridView.EditingControl as dgvNumControl;
                    }
                }            private bool OwnsEditingControl(int rowIndex)
                {
                    if (rowIndex == -1 || this.DataGridView == null)
                    {
                        return false;
                    }
                    dgvNumControl editingControl = this.DataGridView.EditingControl as dgvNumControl;
                    return editingControl != null && rowIndex == ((IDataGridViewEditingControl)editingControl).EditingControlRowIndex;
                }            private void OnCommonChange()
                {
                    if (this.DataGridView != null && !this.DataGridView.IsDisposed && !this.DataGridView.Disposing)
                    {
                        if (this.RowIndex == -1)
                        {
                            this.DataGridView.InvalidateColumn(this.ColumnIndex);
                        }
                        else
                        {
                            this.DataGridView.UpdateCellValue(this.ColumnIndex, this.RowIndex);
                        }
                    }
                }            public override Type EditType
                {
                    get { return defaultEditType; }
                }            public override Type ValueType
                {
                    get
                    {
                        Type valueType = base.ValueType;
                        if (valueType != null)
                        {
                            return valueType;
                        }
                        return defaultValueType;
                    }
                }            public override void InitializeEditingControl(int rowIndex, object initialFormattedValue, DataGridViewCellStyle dataGridViewCellStyle)
                {
                    base.InitializeEditingControl(rowIndex, initialFormattedValue, dataGridViewCellStyle);
                    UbNumBox numEditBox = this.DataGridView.EditingControl as UbNumBox;
                    if (numEditBox != null)
                    {
                        numEditBox.BorderStyle = BorderStyle.None;
                        numEditBox.DecimalLength = this.DecimalLength;
                        numEditBox.MaxValue = this.MaxValue;
                        numEditBox.FromatString = this.FormatString;
                        //numEditBox.AllowNegative = this.AllowNegative;                    string initialFormattedValueStr = initialFormattedValue as string;                    if (string.IsNullOrEmpty(initialFormattedValueStr))
                        {
                            numEditBox.Text = "";
                        }
                        else
                        {
                            numEditBox.Text = LibFunc.ToDecimal(initialFormattedValueStr).ToString(FormatString);
                        }
                    }
                }            [EditorBrowsable(EditorBrowsableState.Advanced)]
                public override void DetachEditingControl()
                {
                    DataGridView dataGridView = this.DataGridView;
                    if (dataGridView == null || dataGridView.EditingControl == null)
                    {
                        throw new InvalidOperationException("Cell is detached or its grid has no editing control.");
                    }                UbNumBox numEditBox = dataGridView.EditingControl as UbNumBox;
                    if (numEditBox != null)
                    {
                        numEditBox.ClearUndo();  // avoid interferences between the editing sessions
                    }                base.DetachEditingControl();
                }            /// <summary>
                /// GridView中的NumberBox变色
                /// </summary>
                /// <param name="graphics"></param>
                /// <param name="clipBounds"></param>
                /// <param name="cellBounds"></param>
                /// <param name="rowIndex"></param>
                /// <param name="elementState"></param>
                /// <param name="value"></param>
                /// <param name="formattedValue"></param>
                /// <param name="errorText"></param>
                /// <param name="cellStyle"></param>
                /// <param name="advancedBorderStyle"></param>
                /// <param name="paintParts"></param>
                protected override void Paint(Graphics graphics,
                   Rectangle clipBounds, Rectangle cellBounds, int rowIndex,
                   DataGridViewElementStates elementState, object value,
                   object formattedValue, string errorText,
                   DataGridViewCellStyle cellStyle,
                   DataGridViewAdvancedBorderStyle advancedBorderStyle,
                   DataGridViewPaintParts paintParts)
                {
                    //可写的时候,单元格变黄色
                    if (!this.ReadOnly)
                    {
                        cellStyle.BackColor = Color.Yellow;
                    }
                    base.Paint(graphics, clipBounds, cellBounds, rowIndex,
                        elementState, value, formattedValue, errorText,
                        cellStyle, advancedBorderStyle, paintParts);
                }
            }
      

  2.   

    WndProc中屏蔽复制
    http://topic.csdn.net/t/20061222/15/5249512.html
      

  3.   

    http://blog.csdn.net/wuyazhe/archive/2010/07/12/5729338.aspx
    稍微修改一点。
    public class IntegerTextbox : TextBox
    {
        protected override void OnKeyPress(KeyPressEventArgs e)
        {
            e.Handled = !(Char.IsNumber(e.KeyChar) || e.KeyChar == (char)8);
            if (!e.Handled) this.Tag = this.Text;//记录最后一次正确输入    
            base.OnKeyPress(e);
        }
        protected override void OnTextChanged(EventArgs e)
        {
            base.OnTextChanged(e);
            if (!System.Text.RegularExpressions.Regex.IsMatch((this).Text, @"^(?!0\d)\d*$"))
            {
                int index = (this).SelectionStart;
                (this).Text = (this).Tag as string;
                (this).SelectionStart = index;
            }
        }
        public const int WM_PASTE = 0x302;
        protected override void WndProc(ref Message m)
        {
            if (m.Msg == WM_PASTE)//粘贴   
            {
                if (!System.Text.RegularExpressions.Regex.IsMatch(Clipboard.GetText(), @"^(?!0\d)\d*$")) return;
            }
            base.WndProc(ref m);
        }
    }如果你允许输入00的情况。可以修改为public class IntegerTextbox : TextBox
    {
        protected override void OnKeyPress(KeyPressEventArgs e)
        {
            e.Handled = !(Char.IsNumber(e.KeyChar) || e.KeyChar == (char)8);
            if (!e.Handled) this.Tag = this.Text;//记录最后一次正确输入    
            base.OnKeyPress(e);
        }
        protected override void OnTextChanged(EventArgs e)
        {
            base.OnTextChanged(e);
            if (!System.Text.RegularExpressions.Regex.IsMatch((this).Text, @"^\d*$"))
            {
                int index = (this).SelectionStart;
                (this).Text = (this).Tag as string;
                (this).SelectionStart = index;
            }
        }
        public const int WM_PASTE = 0x302;
        protected override void WndProc(ref Message m)
        {
            if (m.Msg == WM_PASTE)//粘贴   
            {
                if (!System.Text.RegularExpressions.Regex.IsMatch(Clipboard.GetText(), @"^\d*$")) return;
            }
            base.WndProc(ref m);
        }
    }
      

  4.   

    用你的第二种方法..  光标搞到最后
          
                    
            private int tempStr;
            private void textBox1_TextChanged(object sender, EventArgs e)
            {            if (Regex.IsMatch(textBox1.Text, @"^\d+$") == false)
                {
                    textBox1.Text = tempStr.ToString();
                    this.textBox1.SelectionStart = this.textBox1.TextLength; // 设置光标最后显示
                }
                else
                {
                    tempStr = Convert.ToInt32(textBox1.Text);            }        }
      

  5.   


    用你的第二种方法.. 光标搞到最后
        
      [code=C]    
            private int tempStr; 
            private void textBox1_TextChanged(object sender, EventArgs e) 
            {             if (Regex.IsMatch(textBox1.Text, @"^\d+$") == false) 
                { 
                    textBox1.Text = tempStr.ToString(); 
                    this.textBox1.SelectionStart = this.textBox1.TextLength; // 设置光标最后显示 
                } 
                else 
                { 
                    tempStr = Convert.ToInt32(textBox1.Text);             }         } 
    [/code]
      

  6.   


    用你的第二种方法.. 光标搞到最后
        
       
            private int tempStr; 
            private void textBox1_TextChanged(object sender, EventArgs e) 
            {             if (Regex.IsMatch(textBox1.Text, @"^\d+$") == false) 
                { 
                    textBox1.Text = tempStr.ToString(); 
                    this.textBox1.SelectionStart = this.textBox1.TextLength; // 设置光标最后显示 
                } 
                else 
                { 
                    tempStr = Convert.ToInt32(textBox1.Text);             }         } 
      

  7.   

    各位大哥,我有个几个问题请教你们;
    楼主那个方法一的e.KeyChar != 8是什么意思?
    e.KeyChar = Convert .ToChar (0);能有什么作用?
    还有你那个方法二和方法三中Regex我在控制台应用程序怎么点不出来?
      

  8.   

    感觉还是在WndProc里面过滤一下的好:
    class myTxt : System.Windows.Forms.TextBox
        {
            protected override void WndProc(ref System.Windows.Forms.Message m)
            {
                if(m.Msg == 0x0102) //WM_CHAR
                {
                    switch (m.WParam.ToInt32())
                    { 
                        case 8:     //退格
                        case 13:    //回车
                        case 46:    //删除
                            base.WndProc(ref m);
                            return;
                    }
                    if (m.WParam.ToInt32() < 48 || m.WParam.ToInt32() > 57)
                        return;
                }
                if (m.Msg == 0x0302)    //WM_PASTE
                    return;
                base.WndProc(ref m);
            }
        }
    然后在你的Form里面定义:
    private myTxt textBox1;
    this.textBox1 = new WindowsFormsApplication1.myTxt();
    this.textBox1.Location = new System.Drawing.Point(xx, yy);
    this.textBox1.Name = "textBox1";
    this.textBox1.Size = new System.Drawing.Size(xx, yy);
    this.textBox1.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.textBox1_KeyPress);
      

  9.   

    <script type="text/javascript">
                function clearNoNum(obj)
            {
            //先把非数字的都替换掉,除了数字和.
            obj.value = obj.value.replace(/[^\d.]/g,"");
            //必须保证第一个为数字而不是.
            obj.value = obj.value.replace(/^\./g,"");
            //保证只有出现一个.而没有多个.
            obj.value = obj.value.replace(/\.{2,}/g,".");
            //保证.只出现一次,而不能出现两次以上
            obj.value = obj.value.replace(".","$#$").replace(/\./g,"").replace("$#$",".");
            }
        </script>//Textbox  如下:
    <asp:TextBox ID="TextBox5" Width="60px" onkeyup='clearNoNum(this)' runat="server"></asp:TextBox>
      

  10.   

    最严谨最高效最节省代码的方法:拖一个NumericUpDown控件进去,设置它的Minimun的最小值是0,increment为1即可。
      

  11.   

    我就很奇怪啊,这么个简单的问题让各位高手的代码写了这么长?
    难道我out了?