简体   繁体   中英

checking if dataype is date in bound data

I need to format datetime in a gridview to just show the date. I can't just change the format fo the indiviidual column during the extraction from sql because the code uses the .net generated SqlDataAdapter.Fill. I read on other stackoverflow questions for how to change the date format in bound fields and yet other answers call for using somehting like gridview. Format which intellisense is not finding and is unsurprisingly giving me a no-definition compile error if I try to just type and use it. I can't simply change teh property in the aaspx becuase it is a programatically generated gridview.

Is there a way to enumerate across the columns in the gridview and check if a column is already a datetime type (they will be coming in as datetime from sql, the sort is already working properly so they are not coming in as strings) and change the format on those to just date? currently when I try to enumerate across the columns it skips because the count of columns in the gridview during the data bound is still coming out as 0. Or does anyone have an idea that would be less expensive, these are thousands of rows coming in so it may be much better if I can just format the column or entire gridview for datetime information. thank you

EDIT: I found a way by putting this in the gridview_RowDataBound

                foreach (DataControlFieldCell cell in e.Row.Cells)
                {
                    AutoGeneratedField field = cell.ContainingField as AutoGeneratedField;
                    if (field != null && field.DataType == typeof(DateTime))
                        cell.Text = DateTime.Parse(cell.Text).ToShortDateString();
                }

Even if the SQL is executed by the data adapter, you have the possibility to modify the code in the Select command to transform your datetime field in a string using the Convert function. Something like

SELECT field1, field2,..., fieldN, convert(varchar, getdate(), 103) as mydate

Or, if the SELECT cannot in any way be modified, you can add a field to the datatable on the fly and put the date in string format on that field (but it is time consuming) and can be a solution only if you can hide your gridview columns so to show only the string formatted one.

The better in my opinion is change the select, or much better, if you need a specific view on the data, simply create the correct SQL query with the data you need, call it using a DataReader and create a datatable to Use as source for your gridview, and leave the standard select command to more specific uses. HTH

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM