日期:2014-05-17  浏览次数:20516 次

DataTable修改列值
C# code

/*
比如:在数据库中查询一个DataTable的数据是这样

Name Url CreateTime 
百度 www.baidu.com 2012-5-29 15:49:27 
新浪 www.sina.com 2012-5-29 15:49:27 
谷歌 www.google.com 2012-5-29 15:49:27 

我想在绑定之前将url这一列所有行追加http://,在不循环DataTable的情况下 可以实现吗

想要的结果:
百度 http://www.baidu.com 2012-5-29 15:49:27 
新浪 http://www.sina.com 2012-5-29 15:49:27 
谷歌 http://www.google.com 2012-5-29 15:49:27 
*/



------解决方案--------------------
第一可以通过sql
select Name 'http://'+Url as NewUrl,CreateTime from xxx

第二可以通过GridView1_RowDataBound事件,对这一列加上http,比如
C# code

  protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
  {
      if (e.Row.RowType == DataControlRowType.DataRow)
      {
          e.Row.Cells[0].Text = "http://" + e.Row.Cells[0].Text;
      }
  }

------解决方案--------------------
var list=dt.AsEnumerable().Select(t=>new
{
Name=t.Field<string>("Name"), 
Url=t.Field<string>("Url").StartWith("http")?t.Field<string>("Url"):"http://"+t.Field<string>("Url"),
CreateTime =t.Field<DateTime>("CreateTime ")
});
------解决方案--------------------
正解:
探讨
第一可以通过sql
select Name 'http://'+Url as NewUrl,CreateTime from xxx

第二可以通过GridView1_RowDataBound事件,对这一列加上http,比如

C# code


protected void GridView1_RowDataBound(object sender, GridViewRowEve……

------解决方案--------------------
CreateTime =t.Field<DateTime>("CreateTime ")
这个字段是否为datatime格式,如果不是,改成string