2009-02-26 65 views
4

我有一个DataGridView绑定到DataTable。 DataTable是一个全数字值。要求DataGridView中的每n行都有文本,而不是数字值(以便为用户直观地分隔各个部分)。我很高兴在绑定后将这些文本数据放入DataTable或DataGridView中,但我无法看到将这些文本数据放入其中的方式,因为两种格式都需要数字数据 - 我得到“can not把一个字符串放在一个小数点“的错误。任何想法如何改变DataTable或DataGridView中特定行或单元格的格式?我如何在Winform DataGridView中创建不同的单元格格式#

回答

4

您可以在DataGridView的CellFormatting事件提供一个处理程序,如:

public partial class Form1 : Form 
    { 
     DataGridViewCellStyle _myStyle = new DataGridViewCellStyle(); 

     public Form1() 
     { 
      InitializeComponent(); 

      _myStyle.BackColor = Color.Pink; 
      // We could also provide a custom format string here 
      // with the _myStyle.Format property 
     } 

     private void dataGridView1_CellFormatting(object sender, 
      DataGridViewCellFormattingEventArgs e) 
     { 
      // Every five rows I want my custom format instead 
      // of the default 
      if (e.RowIndex % 5 == 0) 
      { 
       e.CellStyle = _myStyle; 
       e.FormattingApplied = true; 
      } 
     } 

     ... 

有关创建你自己的风格帮助,请参阅DataGridView.CellFormatting Event主题联机帮助中

1

这是否解决问题了吗?

// Set the data source. 
dataGridView1.DataSource = dataTable1; 

// Create a new text box column. 
DataGridViewColumn c1 = new DataGridViewTextBoxColumn(); 
const string C1_COL_NAME = "Custom1"; 
c1.Name = C1_COL_NAME; 

// Insert the new column where needed. 
dataGridView1.Columns.Insert(1, c1); 

// Text can then be placed in the rows of the new column. 
dataGridView1.Rows[0].Cells[C1_COL_NAME].Value = "Some text..."; 

原始数据表绑定应该仍然存在。

相关问题