日期:2014-05-20  浏览次数:20779 次

winform下的datagridview绑定数据时如何更改单元格的值.
比如数据库里有个表示状态的字段,值为数字如:   1   2   3   4   ....
绑定到datagridview显示时要跟据值改成:状态1   状态2   状态3   .......

在Webform里很容易就实现,   在winform里看了半天也不知怎么弄

------解决方案--------------------
select (case when 1 then '状态一 ' when 2 then '状态2 ' end ) as 状态
------解决方案--------------------
for example:

SqlConnection con = new SqlConnection( "server=.;database=student;uid=sa;pwd=0421 ");
SqlDataAdapter sda = new SqlDataAdapter( "select sno,sname,(case sex when 1 then '男 ' when 2 then '女 ' end) as sex from studentDetails ", con);
sda.Fill(ds, "student ");
//绑定
this.dataGridView1.DataSource=ds.Tables[ "student "];
------解决方案--------------------
可以给DataGridView添加CellFormatting事件,
以格式化显示它的单元格的内容,比如:

private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (this.dataGridView1.Columns[e.ColumnIndex].HeaderText == "state ")
{
if (object.Equals(e.Value, 1))
{
e.Value = "状态1 ";
}
else if (object.Equals(e.Value, 2))
{
e.Value = "状态2 ";
}
}
}