进一步this question我正在尝试实现一个DataTable用作DataGridView的数据源。我试图解决的原始问题是DGV会显示来自相当大的对象层次结构的一小部分数字,并且必须反映对这些对象所做的更改。我不能简单地将DGV绑定到源数据。因此,我创建了一个中间DataTable,并在其中填充要在UI中显示的数据,然后将其绑定到DGV。
我现在面临的问题是,尽管所有动态值都是数字,但我显然无法使用DataGridViewCellStyle的Format属性设置这些单元格的显示格式。例如,如果我尝试使用“ ###### 0.000”将数字设置为小数点后三位,则它们将保持不变。因为DataTable的数据类型是'object',所以这并不令我感到特别惊讶。我有意设置此值的原因有两个:1)它必须包含对基础数据的引用,而不是值; 2)内容是文本(保持不变)和数字(将变化)的混合。因此,我认为DGV不会将值视为数字。
绑定是这样完成的:
private void Test_Click(object sender, EventArgs e)
{
DataTable dt = populateDataTable();
BindingSource SBind = new BindingSource();
SBind.DataSource = dt;
dataGridView1.DataSource = SBind;
FormatDGV(dataGridView1);
}
DataTable的填充如下:
private DataTable populateDataTable(int cols, int rows)
{
DataTable custTable = new DataTable("UITable");
for (int i = 0; i < cols; i++)
{
custTable.Columns.Add("", typeof(object));
}
for (int j = 0; j < rows; j++)
{
custTable.Rows.Add(new object[cols]);
}
...然后添加需要在UI中显示的特定信息。文本被添加为对象:
custTable.Rows[1][0] = (object)"foo";
custTable.Rows[4][0] = (object)"bar";
然后我像以前一样尝试设置单元格的样式(预绑定):
dgv[2 + i, 10].Style = greenText;
DataGridViewCellStyle greenText = NewNumberFont(Color.Green, "######0.000");
private DataGridViewCellStyle NewNumberFont(Color fontColor, string numberFormat)
{
DataGridViewCellStyle numberFont = new DataGridViewCellStyle(dataGridView1.DefaultCellStyle);
numberFont.Alignment = DataGridViewContentAlignment.MiddleRight;
Font newFont = new Font(dataGridView1.Font.Name, 15, FontStyle.Regular);
numberFont.Font = newFont;
numberFont.ForeColor = fontColor;
numberFont.Format = numberFormat;
return numberFont;
}
是否有可能使用包含文本和数字混合的中间数据源的这种方法,并且仍然保留对DataGridView中显示的数字格式的控制?
您可以简单地使用事件CellFormatting,然后检查单元格的值(如果它是数字应用于格式
public Form1()
{
InitializeComponent();
this.dataGridView1.CellFormatting += DataGridView1_CellFormatting;
this.dataGridView1.Rows.Add("five");
this.dataGridView1.Rows.Add("235656.5477");
this.dataGridView1.Rows.Add("24.54");
}
private void DataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (Microsoft.VisualBasic.Information.IsNumeric(e.Value))
{
DataGridViewCellStyle numberFont = new DataGridViewCellStyle(dataGridView1.DefaultCellStyle);
numberFont.Alignment = DataGridViewContentAlignment.MiddleRight;
Font newFont = new Font(dataGridView1.Font.Name, 15, FontStyle.Regular);
numberFont.Font = newFont;
numberFont.ForeColor = Color.Red;
numberFont.Format = "{0:#,0.####}";
e.CellStyle = numberFont;
e.Value = string.Format("{0:#,0.####}", Decimal.Parse(e.Value.ToString()));
}
}