2017-06-19 144 views
0

的DataGridView是从DataSource填充:如何替换Datagridview列中的文本?

BindingSource bs = new BindingSource(); 

bs.DataSource = reader.local(); 

dataGridView1.DataSource = bs; 

凡从类模型reader.local();返回数据:

class ClientJson 
    { 

     public int id { get; set; } 
     public string name { get; set; } 
     public string secondname { get; set; } 
     public int sex { get; set; } 
} 

如何在现场sex替换值自定义文本为(男,女)?

回答

1

如果你不想或者不能改变你的模型,你可以使用CellFormatting事件替换单元格的值:

private void dataGridView1_CellFormatting(object sender, System.Windows.Forms.DataGridViewCellFormattingEventArgs e) 
{ 
    if (dataGridView1.Columns[e.ColumnIndex].Name.Equals("sex")) 
    { 
     int? sex = e.Value as int?; 

     // replace statement checks with your own conditions 
     if(sex == 0) 
     { 
      e.Value = "Male"; 
     } 
     else if(sex == 1) 
     { 
      e.Value = "Female"; 
     } 
     else 
     { 
      e.Value = "Unknown"; 
     } 
    } 
} 
0

你有没有考虑过改变属性的类型为“字符串”?

像这样

public string Sex 
{ 
    get 
    { 
     return this.sex; 
    } 
    set 
    { 
     if(value == "1") 
      this.sex = "male"; 
     else 
      this.sex = "female"; 
    } 
} 
0

您可以添加属性只得到进入编辑方针把你的逻辑。一个例子:

public string Gender{ get{ return this.sex==1?"Male":"female";}} 

你只绑定新属性Gender。

0

你是这个意思?

public string Sex 
{ 
    get 
    { 
     return this.sex; 
    } 
    set 
    { 
this.sex=value=="1"?"male":"female"; 
    } 
} 
+0

是,它似乎我需要 – user3573738