2011-08-11 64 views
3

我有一个带有MASTER表的数据库。 MASTER有一列数据类型MONEY的工资。 现在,当我从datagridview中的数据库中获取数据时,我想用“R”显示钱列。附加到它。 像,如果数据库中的薪水是100,我想将它视为Rs。 100在我的datagridview。填充方法只是将整个数据按原样复制到datagridview中。 那么怎么做呢?如何将来自数据库的数据更改为DataGridView

回答

2
dataGridView1.CellFormatting += 
     new System.Windows.Forms.DataGridViewCellFormattingEventHandler(
     this.dataGridView1_CellFormatting); 

private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) 
{ 
    if (this.dataGridView1.Columns[e.ColumnIndex].Name == "Salary") 
    { 
     if (e.Value != null) 
     { 
      try 
      { 
       e.Value = String.Format("Rs. {0:F2}", e.Value); 
       e.FormattingApplied = true; 
      } 
      catch (FormatException) 
      { 
       e.FormattingApplied = false; 
      } 
     } 
    } 
} 
+0

我收到错误 - “名称'格式'不会在当前上下文中出现。” – Sandy

+0

@ user815600 - 对不起,在那里复制/粘贴错误。我更正了这个例子来显示'e'而不是'格式'。 – nekno

+0

完美。它的工作正常。但它给我喜欢,卢比。 100美元,但如何摆脱那个$符号。请耐心等待,我对这种语言和字段 – Sandy

0

上DatabindingComplete您可以手动修改该列(如果您正在使用的WinForms工作)

private void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e) 
    { 
     foreach (DataGridViewRow row in dataGridView1.Rows) 
     { 
      row.Cells["Salary"].Value = "Add your calc here"; 
     } 
    } 
+1

“foreach”可以工作,但这只是在DataGridView被填充后修改列的开销。 – RKh

+0

我同意你的意见。其实我正在寻找“InitializeRow”事件,但后来我意识到我一直在使用Infragistics组件工作太久;) – Martin

+0

实际上,我在数据库中的Salary数据类型是Money。当我添加“Rs”时到我的DatagridView,它给错误,如输入格式是错误的。 – Sandy

1

我不知道,但可以修改使用DataGridView.OnUserAddedRow Method

这里的行添加事件是一个短码。我没有测试它,但请检查是否为你的作品或不:

protected override void OnUserAddedRow(DataGridViewRowEventArgs e) 
{ 
    int actualRowIndex = this.Rows.Count - 2; 
    this.Rows[actualRowIndex].Cells["Salary"].Value = "Rs." + <Your SQL Salary>; 
    base.OnUserAddedRow(e); 
} 

你可以阅读更多有关这种用法在这里:Dynamically set DataGridViewColumn default value at runtime

2

使用列的DefaultCellStyle属性的格式属性题。您可以通过右键单击DataGridView控件,使用“编辑列”对话框以声明方式进行操作。在你的情况下,你需要将Format属性设置为'Rs'。 0.00。需要单引号才能在Rs之后转义点号。

有关更多信息,请阅读MSDN上的Custom Numeric Format Strings主题。

相关问题