You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C# WinForms自定义DataGridView特定列显示文本的实现需求

需求实现:DataGridView列值转换显示

我使用C# WinForms框架,通过API接口获取数据并绑定到DataGridView控件。需要实现:将DataGridView中的Situation列,当值为"1"时显示为"Tamir",值为"0"时显示为"Hazır"。

DataGridView截图

现有代码

PostResponse.cs

public class ProductData 
{
    [JsonProperty("type_name")]
    public int Id { get; set; }
    public string Title{ get; set; }
    public string Description { get; set; }
    public string Situation { get; set; }
    public string Type_Name { get; set; }
    
}

public class ProductDataFeatures 
{
    [JsonProperty("products_type_feature_id")]
    public string Products_Type_Feature_Id { get; set; }
    public string Feature_Name { get; set; }
    public string Feature_Unit_Name { get; set; }
    public string Feature { get; set; }
}

Form1_Load方法

public async void Form1_Load(object sender, EventArgs e)
{
    try
    {
        var postData = new PostData
        {
            id = 5,
            title = "yeni",
            description = "yenidesc",
            type_name = "yenitype"
        };

        var client = new HttpClient();
        client.BaseAddress = new Uri("i_know_what_must_be_here");

        var json = JsonConvert.SerializeObject(postData);
        var content = new StringContent(json, Encoding.UTF8, "application/json");

        var response = client.PostAsync("products", content).Result;

        if (response.IsSuccessStatusCode)
        {
            var responseContent = await response.Content.ReadAsStringAsync();
            var postResponse = JsonConvert.DeserializeObject<PostResponse>(responseContent); //JsonSerializer.Deserialize<PostResponse>(responseContent);
            dataGridView1.DataSource = postResponse.Products;
            dataGridView1.Refresh();
        }
        else
        {
            MessageBox.Show("Hata: " + response.StatusCode);
        }
    }
    catch (Exception error)
    {
        MessageBox.Show(error.Message);
    }
}

实现方案

方法1:实体类新增显示属性(推荐)

在ProductData类中添加只读属性,直接返回转换后的文本,后续绑定DataGridView时使用该属性:

public class ProductData 
{
    [JsonProperty("type_name")]
    public int Id { get; set; }
    public string Title{ get; set; }
    public string Description { get; set; }
    public string Situation { get; set; }
    public string Type_Name { get; set; }
    
    // 新增转换后的显示属性
    public string SituationDisplay
    {
        get 
        {
            return Situation switch
            {
                "1" => "Tamir",
                "0" => "Hazır",
                _ => Situation
            };
        }
    }
}

绑定数据后,在DataGridView中隐藏原Situation列,显示SituationDisplay列即可。

方法2:利用CellFormatting事件处理

在窗体构造函数中绑定CellFormatting事件,在事件内对指定列的值进行转换:

public Form1()
{
    InitializeComponent();
    // 绑定单元格格式化事件
    dataGridView1.CellFormatting += DataGridView1_CellFormatting;
}

private void DataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    // 确认当前列是Situation列(可根据列名或索引判断)
    if (dataGridView1.Columns[e.ColumnIndex].Name == "Situation" && e.Value != null)
    {
        string value = e.Value.ToString();
        e.Value = value switch
        {
            "1" => "Tamir",
            "0" => "Hazır",
            _ => value
        };
        // 标记格式已处理,避免重复格式化
        e.FormattingApplied = true;
    }
}

这种方式无需修改实体类,直接在界面层处理显示逻辑。

方法3:DataTable中间转换

将实体列表转换为DataTable,修改对应列值后再绑定到DataGridView:

if (response.IsSuccessStatusCode)
{
    var responseContent = await response.Content.ReadAsStringAsync();
    var postResponse = JsonConvert.DeserializeObject<PostResponse>(responseContent);
    
    DataTable dt = new DataTable();
    dt.Columns.Add("Id", typeof(int));
    dt.Columns.Add("Title", typeof(string));
    dt.Columns.Add("Description", typeof(string));
    dt.Columns.Add("Situation", typeof(string));
    dt.Columns.Add("Type_Name", typeof(string));
    
    foreach (var product in postResponse.Products)
    {
        string displayValue = product.Situation switch
        {
            "1" => "Tamir",
            "0" => "Hazır",
            _ => product.Situation
        };
        dt.Rows.Add(product.Id, product.Title, product.Description, displayValue, product.Type_Name);
    }
    
    dataGridView1.DataSource = dt;
    dataGridView1.Refresh();
}

内容的提问来源于stack exchange,提问作者gb00-

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 13:52:48