当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - Dataset datatable formatting rows

问题描述:

Hi i have a dataset which contains a table retrieved from sql. It has 'product' column and 'price' column. I got the dataset and binded to grid. Now i want to make the grid's price column to be formatted to 2 decimal places(validation). Any idea please.

I should not change the select query since its an SP which gives me the dataset.

网友答案:

if you neither want to use Bound-Field nor change select query than as much i know you have two options left to accomplish this. First is, do value change in your dataset before binding to grid using any loop and the second option is alter values in grid on RowDataBound Event...

By altering value in Dataset:

 foreach(dataRow[] dr in dataset.tables[your table index])
 {
  // max. two decimal places
   string val =   String.Format("{0:0.##}",Convert.ToDecimal(dr[column index])); 
   dr[column index] = val;
 }

By altering value in Grid:

  protected void mygrid_OnRowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            mygrid.cell[cell index].Text =   String.Format("{0:0.##}",Convert.ToDecimal(dataset.tables[table index][column index][Row Index]));               

        }
    }

Now if you want apply validation for data insert and update you can apply RegularExpressionValidator at your textBox ...

   <EditItemTemplate>
  <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"     ErrorMessage="RegularExpressionValidator"
        ControlToValidate="TextBox1" ValidationExpression="^\d{1,2}([.]\d{1})$"> ValidationGroup="MyVal"</asp:RegularExpressionValidator>

Now you have to apply

ValidationGroup="MyVal"

also on click control on which you'll perform its editing and update..

网友答案:

Try this:

<asp:BoundField DataField="Price" DataFormatString="{0:C2}" HeaderText="Price" />

You need to add the "DataFormatString" property to the bound field as shown above. This formats currency values to two decimal places. Check this article.

DataField refers to the name of the column in the datatable, whereas the HeaderText refers to the text which would be shown as the header of the column in grid.

分享给朋友:
您可能感兴趣的文章:
随机阅读: