//調用
private void InsertNull()
{
try
{
………………
DataTable Dtab = myDs.Tables[0];
dataGrid1.DataSource =Dtab;
// 把數字值替換成字符串顯示
ChangeSomeView(Dtab);
//設定列名 中文顯示
SetHeaderName(Dtab.TableName); //處理難點 tablename必須對應才能顯示出中文列名
}
catch (Exception err)
{
MessageBox.Show(this,err.Message,"",MessageBoxButtons.OK,MessageBoxIcon.Error);
}
}
#region/**中文列名****/
/// <summary>
/// 將DataGrid中的列名替換成中文
/// </summary>
private void SetHeaderName(string tablename)
{
//重新定制datagrid1的列名
SetupGrid(this.dataGrid1, m_sAryColName, m_sAryColText,m_sAryColWidth,tablename);
}
#endregion
#region/***設置表頭***/
private void SetupGrid(DataGrid AGrid,string[] sAryColName,string[] sAryColText,
int[] sAryColWidth,string ATableName)
{
try
{
//列名,列題頭,列寬
int iCount=sAryColText.Length; //sAryColName.Length;
//
DataGridTableStyle tblStyle= new DataGridTableStyle();
tblStyle.MappingName= ATableName;
DataGridTextBoxColumn[] fldStyleAry=new DataGridTextBoxColumn[iCount];
for(int i=0;i<fldStyleAry.Length;i++)
{
fldStyleAry[i]=new DataGridTextBoxColumn();
}
tblStyle.GridColumnStyles.AddRange(fldStyleAry);
AGrid.TableStyles.Clear();
AGrid.TableStyles.Add(tblStyle);
tblStyle.DataGrid=AGrid;
tblStyle.ReadOnly=true;
for(int i=0;i<sAryColName.Length;i++)
{
DataGridTextBoxColumn NumberColumn = fldStyleAry[i];
NumberColumn.MappingName = sAryColName[i];
NumberColumn.HeaderText = sAryColText[i];
NumberColumn.Width = AGrid.Width/iCount; //平均分配 原來 =sAryColWidth[i];
}
}
catch
{
throw;
}
}
//數據庫中的字段
string [] m_sAryColName=new String[]
{
"ID","Type", "Customer_name","Sex","Identity_card' ……………… };
//對應到Grid上的中文名稱
string[] m_sAryColText=new String[]
{
"順序號", "類型","客戶姓名","性別", "身份證號 ………… };
//顯示的寬度
int[] m_sAryColWidth=new int[]
{
20,20,100,10,150,150,150,150,150,150,200,150,200,150 //亂給的
};
#endregion
方法二:select ID as 順序號 ,cstr(Type) as 類型 …… 完成列名顯示中文的功能。
另外的壹個小技巧 :select ID ,cstr(Type) as Type 將Type 由INT 提取的時候cstr,然後才能完成替換後的回寫
/// <summary>
/// 把數字值替換成字符串顯示 1---學生表
/// </summary>
/// <param name="Dtab">DataTable Dtab</param>
private void ChangeSomeView(DataTable Dtab)
{
foreach(DataRow Row in Dtab.Rows)
{
object IDType=Row[1];
string operStr=IDType.ToString();
switch(operStr)
{
case "1" :
Row[1] = "學生表" ;
break;
…… }
}
}