Original data:
Translated data:
Generally, it is easy to query and display a DataTable in the code, as long as the queried DataTable is used as the DataSource of a certain control, it is OK, but the fields of this DataTable are all English fields, how to change them all to Chinese?
Now I know the Chinese names of each English field, and all the translation information of the fields is stored in a table, called COLUMNTRANSLATION, and the SQL statement to create this table is:
create table COLUMNTRANSLATION
( ID NUMBER(10) PRIMARY KEY, COLUMNNAME VARCHAR2(50), //field name TRANSLATION VARCHAR2(50) // field corresponding to the Chinese name
)
Put a few data in it first, so that there are several records in this table, for example: StudentName corresponds to "student name".
Now that I have a DataTable with all its field names in English, I can translate it and return the translated DataTable by simply executing the following code:
- /// <summary>
- /// 将DataTable的字段名全部翻译为中文
- /// </summary>
- /// <param name="table">待翻译的DataTable</param>
- /// <returns></returns>
- public DataTable TranslateDataTable(DataTable table)
- {
- DataTable dt = new DataTable();
- dt.TableName = "TempTable";
- if (table != null && table.Rows.Count > 0)
- {
- //先为dt构造列信息
- foreach (DataColumn column in table.Columns)
- {
- string name = GetColumnName(column.ColumnName);
- dt.Columns.Add(name);
- }
- for (int i = 0; i < table.Rows.Count; i++)
- {
- DataRow NewRow = dt.NewRow();
- DataRow row = table.Rows[i];
- for (int j = 0; j < dt.Columns.Count; j++)
- {
- NewRow[j] = row[j].ToString();
- }
- dt.Rows.Add(NewRow);
- }
- }
- return dt;
- }
- /// <summary>
- /// 得到列名称的别名
- /// </summary>
- /// <param name="columnName"></param>
- /// <returns></returns>
- private string GetColumnName(string columnName)
- {
- string sqlString = " Select TRANSLATION from COLUMNTRANSLATION where COLUMNNAME = '" + columnName.ToUpper() + "'";
- object s = dao.ExecuteScalar(sqlString);
- string name = (s == null) ? columnName : s.ToString(); //如果此英文字段有翻译,则返回其中文翻译,若无,则保留此英文翻译。
- return name;
- }
Copy code The idea of this method is to construct a new DataTable according to the DataTable to be translated: the column name of each column of the new DataTable is the translated Chinese name (if the English column name is not translated, the English column name is retained, if it can be translated, it is translated), and after constructing the field information of the new DataTable, the records of the old DataTable are inserted into the new DataTable one by one.
Hehe, it's a turn... But speed is still possible.
|