【问题标题】:How to replace text in column Datagridview?如何替换Datagridview列中的文本?
【发布时间】:2017-06-19 06:59:39
【问题描述】:

我有从DataSource 填充的 DataGridView

BindingSource bs = new BindingSource();

bs.DataSource = reader.local();

dataGridView1.DataSource = bs;

reader.local(); 从 Model 类返回数据:

class ClientJson
    {

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

如何将字段sex中的值替换为自定义文本为(男性,女性)?

【问题讨论】:

    标签: c# winforms c#-4.0 datagridview


    【解决方案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";
            }
        }
    }
    

    【讨论】:

      【解决方案2】:

      您是否考虑过将属性的类型更改为“字符串”?

      类似的东西

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

      【讨论】:

        【解决方案3】:

        你可以添加一个只有 get 和 into thist put 你逻辑的属性。一个例子:

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

        你只绑定新属性 Gender。

        【讨论】:

          【解决方案4】:

          你的意思是这样吗?

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

          【讨论】:

          • 是的,看来我需要
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-09-13
          • 2013-04-26
          • 1970-01-01
          • 2010-10-08
          • 2011-07-10
          相关资源
          最近更新 更多