C# WinForm DataGridView 给标题列增加序号及格式化某个字段
DataGridView 给标题列增加序号
代码
private void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
DataGridViewTextBoxColumn dgv_Text = new DataGridViewTextBoxColumn();
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
int j = i + 1;
dataGridView1.Rows[i].HeaderCell.Value = j.ToString();
}
}
{
DataGridViewTextBoxColumn dgv_Text = new DataGridViewTextBoxColumn();
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
int j = i + 1;
dataGridView1.Rows[i].HeaderCell.Value = j.ToString();
}
}
格式化某个字段
代码
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if ( e == null || e.Value == null || !(sender is DataGridView) )
{
return;
}
DataGridView dgv = (DataGridView)sender;
object originalValue = e.Value;
if(dgv.Columns[e.ColumnIndex].DataPropertyName == "操作类型")
{
e.Value = ((int)originalValue == 1) ? "缴费" : "退费";
}
if (e.ColumnIndex == dgv.Columns["Apply_Date"].Index) //格式化日期
{
if (e.Value != null)
{
e.Value = Convert.ToDateTime(e.Value).ToString("yyyy-M-d");
}
}
}
{
if ( e == null || e.Value == null || !(sender is DataGridView) )
{
return;
}
DataGridView dgv = (DataGridView)sender;
object originalValue = e.Value;
if(dgv.Columns[e.ColumnIndex].DataPropertyName == "操作类型")
{
e.Value = ((int)originalValue == 1) ? "缴费" : "退费";
}
if (e.ColumnIndex == dgv.Columns["Apply_Date"].Index) //格式化日期
{
if (e.Value != null)
{
e.Value = Convert.ToDateTime(e.Value).ToString("yyyy-M-d");
}
}
}