2005如何格式化dataGridView中某個字段的值?
1,如何格式化dataGridView中某個字段的值,如:
性別
1
1
0
1
想要格式化為:
性別
男
男
女
男
=======================
2,如何設定某個字段居中對齊?
3,如何將字段按要求重新來排列?
姓名,性別,出生日期====> 姓名,出生日期,性別
------解决方案--------------------1. 请用Key/Value Pair的Collection实现, 或者用enum
2. 请用CellStyle里面的Alignment
3. 参考Sort(IComparer)
------解决方案--------------------TO:1,如何格式化dataGridView中某個字段的值
可以给DataGridView添加CellFormatting事件,以格式化显示它的单元格的内容,比如:
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (this.dataGridView1.Columns[e.ColumnIndex].HeaderText == "sex ")
{
if (object.Equals(e.Value, 1))
{
e.Value = "男 ";
}
else if (object.Equals(e.Value, 0))
{
e.Value = "女 ";
}
}
}
------解决方案--------------------TO:2,如何設定某個字段居中對齊?
for example:
this.dataGridView1.Columns[ "列名 "].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
------解决方案--------------------TO:3,如何將字段按要求重新來排列?
你的意思是不是自定义表头??
for example:
private void Form1_Load(object sender, EventArgs e)
{
DataBind();
}
private void DataBind()
{
//初始化DataGridView
DataGridViewTextBoxColumn column = new DataGridViewTextBoxColumn();
column.Name = "sno ";
column.HeaderText = "学号 ";
//设置绑定数据源的sno字段
column.DataPropertyName = "sno ";
this.dataGridView1.Columns.Add(column);
column = new DataGridViewTextBoxColumn();
column.Name = "sname ";
column.HeaderText = "姓名 ";
//设置绑定数据源的sname字段
column.DataPropertyName = "sname ";
this.dataGridView1.Columns.Add(column);
column = new DataGridViewTextBoxColumn();
column.Name = "sage ";
column.HeaderText = "年龄 ";
//设置绑定数据源的 "sage "字段
column.DataPropertyName = "sage ";
this.dataGridView1.Columns.Add(column);
//设置不自动产生列
this.dataGridView1.AutoGenerateColumns = false;
this.dataGridView1.AllowUserToAddRows = false;
//以下进行数据绑定
SqlConnection con = new SqlConnection( "server=.;database=student;uid=sa;pwd=0421 ");
SqlDataAdapter sda = new SqlDataAdapter( "select * from studentDetails ", con);
DataSet ds = new DataSet();
sda.Fill(ds, "student ");
this.dataGridView1.DataSource = ds.Tables[ "student "];
}
------解决方案--------------------方法一
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (this.dataGridView1.Columns[e.ColumnIndex].HeaderText == "sex ")
{
if (object.Equals(e.Value, 1))
{
e.Value = "男 ";
}
else if (object.Equals(e.Value, 0))
{
e.Value = "女 ";
}
}
}
方法二
在datagirdview中加入combox列