2 zhaojuntaow zhaojuntaow 于 2014.07.02 21:11 提问

C# Mysql datagridview控件 列标题中文乱码问题

用C#从Mysql中读取数据到datagridview控件中,结果列标题中文乱码,内容没事。代码如下:
string commstr = "SELECT Patient_ID as ID,NAME as 姓名,TARGET as 患侧,DIAGNOSIS as 诊断 FROM PatientInfo";
this.data_case.DataSource = DBOperate.DBOperate.selectData(commstr, 数据库.DBConnection.SqlConnstr);
int rows = this.data_case.RowCount - 1;
for (int i = 0; i < rows; i++)
{
if (this.data_case.Rows[i].Cells[2].Value.ToString() == "L")
this.data_case.Rows[i].Cells[2].Value = "左手";
else
this.data_case.Rows[i].Cells[2].Value = "右手";
}
列标题名称本来应该是ID 姓名 患侧 诊断 的,但出现了中文乱码。我在DOS下对MySQL进行数据库查询操作,同样查询命令"SELECT Patient_ID as ID,NAME as 姓名,TARGET as 患侧,DIAGNOSIS as 诊断 FROM PatientInfo"的标题是ID 姓名 患侧 诊断,没有乱码。这是哪里出了问题,要怎么解决呢?

1个回答

zhaojuntaow
zhaojuntaow   2014.07.03 22:27

我已经解决了,但是程序会显得不简洁,不易读,这后续再优化吧……
DataColumn newDC;
DataTable dt = new DataTable();
newDC = new DataColumn("ID", System.Type.GetType("System.String"));
dt.Columns.Add(newDC);
newDC = new DataColumn("姓名", System.Type.GetType("System.String"));
dt.Columns.Add(newDC);
newDC = new DataColumn("患侧", System.Type.GetType("System.String"));
dt.Columns.Add(newDC);
newDC = new DataColumn("诊断", System.Type.GetType("System.String"));
dt.Columns.Add(newDC);
string commstr = "SELECT Patient_ID,Name,TARGET,DIAGNOSIS FROM PatientInfo";
string connstr = "server=localhost;user id=root;Password=;database=RehabilitationDB1";
MySqlConnection conn = new MySqlConnection(connstr);
//dt.Clear();
conn.Open();
MySqlCommand cmd = new MySqlCommand(commstr, conn);
MySqlDataReader mysqlreader = cmd.ExecuteReader();
while (mysqlreader.Read())
{
string ID = mysqlreader["Patient_ID"].ToString();
string name = mysqlreader["Name"].ToString();
string target = mysqlreader["Target"].ToString();
string diagnosis = mysqlreader["Diagnosis"].ToString();
DataRow newDR;
newDR = dt.NewRow();
newDR["ID"] = ID;
newDR["姓名"] = name;
newDR["患侧"] = target;
newDR["诊断"] = diagnosis;
dt.Rows.Add(newDR);
}
conn.Close();
this.data_case.DataSource = dt;
希望可以帮助大家~~

Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!