如何改变datagridview的列日期格式时,GridView控件具有的AutoGenerateColumns =真 [英] How to change datagridview column date format when gridview has autogeneratecolumns=true
问题描述
我这取决于搜索参数是自动生成列的GridView,几列将被添加或删除。
I am auto generating columns in gridview depending on search parameters, few columns will be added or removed.
请给我建议的方式来设置日期格式 DD-MMM-YYYY
在GridView的整列。
Please suggest me a way to set the date format to dd-mmm-yyyy
for entire column in gridview.
现在,我使用的RowDataBound
这样做。它会检查每行,所以它需要时间来显示结果。
For now, I'm doing it using rowdatabound
. It checks every row, So it takes time to show the results.
这是我在的RowDataBound
<做/ p>
This is what I do in rowdatabound
if (e.Row.RowType == DataControlRowType.DataRow)
{
System.Data.DataRowView dtview;
DateTime dt;
int intCounter;
dtview = (DataRowView)e.Row.DataItem;
for (intCounter = 0; intCounter <= dtview.Row.ItemArray.Length - 1; intCounter++)
{
if (dtview.Row.ItemArray[intCounter] is System.DateTime)
{
dt = (DateTime)dtview.Row.ItemArray[intCounter];
e.Row.Cells[intCounter].Text = dt.ToString("dd-MMM-yyyy");
}
}
}
这将检查所有记录和然后根据病情变化。
This checks for all records and then changes based on condition.
但我想做得更好,只是通过标识列和更改完成列中的日期格式。
But I want to do it better, just by identifying the column and change the date format for complete column.
推荐答案
我有点晚了。但是,这为我工作。它仍然使用的RowDataBound()方法。但它只能运行针对数据源中的第一行。
I'm a little late. But this worked for me. It still uses the RowDataBound() method. But it only runs against the first row in the data source.
protected void gvGridView_RowDataBound(Object sender, GridViewRowEventArgs e)
{
DataRowView drv = (DataRowView)e.Row.DataItem;
if (e.Row.RowType == DataControlRowType.DataRow)
{
for (int i = 0; i < ct_columns; i++)
{
DataControlFieldCell dcf = e.Row.Cells[i] as DataControlFieldCell;
/* default date format: hide 'time' values */
if (e.Row.RowIndex == 0
&& (dcf.ContainingField.GetType().Name == "BoundField" // defined columns
|| dcf.ContainingField.GetType().Name == "AutoGeneratedField")) // auto-generated columns
{
BoundField bf = dcf.ContainingField as BoundField;
if (bf != null && String.IsNullOrEmpty(bf.DataFormatString))
{
string col_name = bf.DataField;
if (!String.IsNullOrEmpty(col_name) && drv[col_name] != null)
{
if (drv[col_name].GetType().Name == "DateTime")
{
// set format for first row
string date = drv[col_name].ToString();
if (!String.IsNullOrEmpty(date))
dcf.Text = DateTime.Parse(date).ToShortDateString();
// set format for other rows
bf.DataFormatString = "{0:M/dd/yyyy}";
}
}
}
}
}
}
}
这篇关于如何改变datagridview的列日期格式时,GridView控件具有的AutoGenerateColumns =真的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!