首先要搞清楚,当你在datagrid中输入数据时
实际上通过内嵌在该列的textbox与之交互的。
所以,第一问题解决:this.datagrid1.tablestyle[0].gridcolumnstyle.TextBox.KeyPress += new KeyPressEventHandler(textBox1_KeyPress);
private bool IsMatch(string str)
{
if(str != "")
{ System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex("^[0-9]*$");
return regex.IsMatch(str);
}
return true;
}private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
if(e.KeyChar == (Char)8||e.KeyChar == (Char)13)//不屏蔽退格键和回车键
return;
try
{
e.Handled = !IsMatch(e.KeyChar.ToString());
}
catch
{  
}
}

解决方案 »

  1.   

    二:同样,你把该textbox的readonly设为true,这样用户也就不能编辑该列的数据。
    至于要该它的颜色的话,就有一写麻烦,这需要你重写它的paint方法。
    给你个例子。
    public class DataGridColoredTextBoxColumn : DataGridTextBoxColumn 
      { 
     
        protected override void Paint(System.Drawing.Graphics g, 
        System.Drawing.Rectangle bounds, System.Windows.Forms.CurrencyManager 
         source, int rowNum, System.Drawing.Brush backBrush, System.Drawing.Brush
         foreBrush, bool alignToRight) 
            { 
     
                   try{ 
     
                        object o = this.GetColumnValueAtRow(source, rowNum); 
                        if( o!= null) 
                        { 
                             char c = ((string)o)[0]; 
                             if( c > 'F') 
                             { 
                                  backBrush = new LinearGradientBrush(bounds, 
                                       Color.FromArgb(255, 200, 200), 
                                      Color.FromArgb(128, 20, 20), 
                                       LinearGradientMode.BackwardDiagonal); 
                                  foreBrush = new SolidBrush(Color.White); 
                             } 
                        } 
                   } 
                    catch(Exception ex){ /* empty catch */ } 
                   finally{                 
                        base.Paint(g, bounds, source, rowNum, backBrush, foreBrush, alignToRight);  
                   } 
     
              } 
     
         } 
     
      

  2.   

    三:用datagrid.select(int i);
    这个i就要你自己算了。
      

  3.   

    this.bindingtext[this.datagrid.datasource,this.datagrid.datamember].position = int i;
    是把i行设为当前行。
      

  4.   

    作答第三个问题
    int i =datagrid.CurrentRowIndex()
    i就是你选择的行的索引
      

  5.   

    楼主的第三个问题大概不是要取当前选中的行,而是要先按照某个字段定位,然后将光标移动到那行。
    还有第二个问题,既然可以把textbox的readonly属性设置为true,为什么不能将backcolor属性设置为想要的颜色呢?何必重写paint方法呢?
      

  6.   

    这个问题有很多人问了
     Henry手记— WinForm Datagrid结构剖析
    http://www.yestar2000.com/TechCenter/TCSubCate.asp?SubID=1408