有時候我們會遇到在DataGrid中動態綁定某個字段的情況,比如:當顯示中文時我們綁定cname,顯示英文時我們要綁定ename,此時我們可以這樣:
ButtonColumn:
if (language == "cn")
((ButtonColumn)this.DataGrid1.Columns[3]).DataTextField = "cname";
else
((ButtonColumn)this.DataGrid1.Columns[3]).DataTextField = "ename";
BoundColumn:
((BoundColumn)this.DataGrid1.Columns[3]).DataField = "cname";
HyperLinkColumn同ButtonColumn的寫法,不同的是當我們要動態改變TemplateColumn的顯示應該怎麼辦呢?
這樣就行了 先新建一個模板:
public class Template1 :ITemplate
{
public void InstantiateIn(Control container)
{
TextBox txt = new TextBox();
txt.Text = "this is a added template column";
container.Controls.Add(txt);
}
}
再這樣寫:
((TemplateColumn)this.DataGrid1.Columns[1]).ItemTemplate = new Template1();
2.動態轉換DataGrid中某個Cell中的值
BoundColumn:
if (e.Item.Cells[3].Text == "Ann")
e.Item.Cells[3].Text = "<b>這一行本來應該顯示Ann,現在被轉換成這樣了!</b>";
ButtonColumn :
LinkButton link = (LinkButton)e.Item.Cells[3].Controls[0];
if (link.Text == "Ann")
link.Text = "<b>這一行本來應該顯示Ann,現在被轉換成這樣了!</b>";
這段代碼寫在:OnItemDataBound事件的方法體中就可以了.
HyperLinkColumn:
強類型轉換成HyperLink,
Template Column:
通過FindControl方法
3.動態創建DataGrid及添加列
DataGrid dg = new DataGrid();
// BoundColumn
BoundColumn col1 = new BoundColumn();
col1.DataField = "au_id";
col1.HeaderText = "au_id";
dg.Columns.Add(col1);
// ButtonColumn
ButtonColumn col2 = new ButtonColumn();
col2.DataTextField = "au_fname";
col2.HeaderText = "au_fname";
dg.Columns.Add(col2);
// TemplateColumn
TemplateColumn col3 = new TemplateColumn();
col3.ItemTemplate = new Templates.Template1();
col3.HeaderText = "My Template Column";
dg.Columns.Add(col3);
// LinkButtonColumn
HyperLinkColumn col4 = new HyperLinkColumn();
col4.HeaderText = "au_lname";
col4.DataTextField = "au_lname";
col4.DataNavigateUrlField = "au_lname";
dg.Columns.AddAt(0,col4);
SqlConnection conn = new SqlConnection("server=localhost;uid=sa;pwd=;database=pubs");
SqlDataAdapter da = new SqlDataAdapter("select * from authors",conn);
DataSet ds = new DataSet();
da.Fill(ds);
dg.DataSource = ds;
dg.DataBind();
Page.Controls[1].Controls.Add(dg);
4.關於.Net中將DataGrid內容導出到Excel亂碼的問題
一般常用的方法爲:
DataGrid1.DataSource = this.GetDataSource();
DataGrid1.DataBind();
Response.Clear();
Response.Buffer = true;
Response.ContentType = "application/vnd.ms-excel";
Response.Charset = "gb2312";
EnableViewState = false;
System.IO.StringWriter tw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
DataGrid1.RenderControl(hw );
Response.Write(tw.ToString());
Response.End();
但是有時導出會出現亂碼,有時則不會出現亂碼.真是百思不得其解.
我們可以這樣解決將
Response.ContentType = "application/vnd.ms-excel";
Response.Charset = "gb2312";
換成:
Response.Write("<meta http-equiv=Content-Type content=text/html;charset=gb2312>");
Response.AppendHeader("content-disposition","attachment;filename=/"" + HttpUtility.UrlEncode("全部銷售記錄["+DateTime.Now.ToString("yyyy-MM-dd")+"]",System.Text.Encoding.UTF8) + ".xls/"");