I have modified data in a datatable. How do I get this modified data back into the table?

72 views Asked by At

I have modified data in a datatable. The column ExpireDate returns date + time although I needed Date only. I am successfully reading through each row to return the correct format, but how do I get this modified date column back into the table so I can display it in my web form?

con.Open();
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
    {
       DataTable dt = new DataTable();                           
       foreach (DataRow dr in dt.Rows)
       {
          dr["ExpireDate"] = DateTime.Parse((dr["ExpireDate"].ToString())).ToShortDateString();
       }                                                      
       sda.Fill(dt);
       tblBoard.DataSource = dt;
       tblBoard.DataBind();
       con.Close();
    }

Here's the web form:

<asp:GridView ID="tblBoard" runat="server" AutoGenerateColumns="false">
    <Columns>                
        <asp:BoundField DataField="FirstName" HeaderText="First Name" />
        <asp:BoundField DataField="LastName" HeaderText="Last Name" />
        <asp:BoundField DataField="ExpireDate" HeaderText="Expire Date" />               
    </Columns>
</asp:GridView>

The old date format is still showing in the table.

2

There are 2 answers

0
Grant Winney On BEST ANSWER

Don't change the value stored in the DataTable itself... instead, modify how it appears when displayed to the user by specifying a DataFormatString:

<asp:BoundField DataField="ExpireDate"
                HeaderText="Expire Date"
                DataFormatString="{0:dd/MM/yyyy}" />

The data and the presentation of the data are two distinct things. I guess you could use a string column and then just display the part of the date you want to show, but using the format is better since someone could easily step in and change how the date is displayed in the future without touching the data.

0
A.M. Patel On

If you change the date format from backend and that date not reflect in front end then once try to remove catch of your browser and then try again.

Also, one more solution is no need to use for loop in backend. Directly bind your table data to grid view data source and front end set DataFormatString only.

<asp:BoundField DataField="ExpireDate" HtmlEncode="false" 
DataFormatString="{0:d}" />

or

<asp:BoundField DataField="ExpireDate" HtmlEncode="false" 
 DataFormatString="{0:MM/dd/yyyy}" />