【问题标题】:Replace data while update in datagrid view using c#使用c#在datagrid视图中更新时替换数据
【发布时间】:2019-05-17 01:43:28
【问题描述】:

上图 0 和 1 来自数据库,同时在数据网格视图中显示值 1 被替换为高,0 被替换为低我不知道这有助于我解决这个问题

            con.Open();
            SqlCommand cmd = con.CreateCommand();
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "select dataa from new";
            cmd.ExecuteNonQuery();
            DataTable dt = new DataTable();
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            da.Fill(dt);
            dataGridView1.DataSource = dt;
            con.Close();

【问题讨论】:

  • 可以分享一下实际的sql查询吗?
  • 这是一个实际查询,这是示例应用程序,所以我创建了一列
  • 可以在sql查询中使用CASE WHEN。 Read here
  • 非常感谢

标签: c# mysql .net winforms datagridview


【解决方案1】:

您可以使用不同的解决方案来处理此案,包括:

  • 使用 DataGridViewComboBoxColumn(→ 如果需要编辑,请首选)
  • 使用 CellFormatting(→ 如果您不需要编辑,则首选)
  • 更改查询以返回格式化数据(→ 对只读数据有用)

选项 1 - 使用 DataGridViewComboBoxColumn

添加DataGridViewComboBoxColumn:

var c = new DataGridViewComboBoxColumn();
c.DataPropertyName = "Column1"; //Name of your data column
c.HeaderText = "Column1";       //Header text of your data column
c.DataSource = new[] {
    new { Key = 0, Name = "Low" },
    new { Key = 1, Name = "High" } }.ToList();
c.ValueMember = "Key";
c.DisplayMember = "Name";
c.DisplayStyle = DataGridViewComboBoxDisplayStyle.Nothing;  
//You can try other styles as well as setting `ReadOnly` to true
dataGridView1.Columns.Add(c);

选项 2 - 使用单元格格式化

另一种选择是使用CellFormatting 事件:

dataGridView1.CellFormatting += (obj, args) =>
{
    try
    {
        var value = Convert.ToInt32(args.Value);
        if (value == 0)
            args.Value = "Low";
        if (value == 1)
            args.Value = "High";
        return;
    }
    catch (Exception) { }
    args.Value = "Unknown";
};

选项 3 - 更改查询

您可以更改查询以获取格式化数据,例如使用CASE

SELECT CASE [YourColumn] WHEN 1 THEN 'High' WHEN 2 THEN 'Low' END AS Column1
FROM [YourTable]

示例输出

对于以上所有代码,您可以从数据库加载数据或仅用于测试使用以下测试数据:*

var dt = new DataTable();
dt.Columns.Add("Column1", typeof(int));
dt.Rows.Add(1);
dt.Rows.Add(0);
dt.Rows.Add(0);
dt.Rows.Add(1);

并确保您设置了数据源:

dataGridView1.DataSource = dt;

【讨论】:

    猜你喜欢
    • 2013-06-25
    • 2019-06-21
    • 2013-12-25
    • 1970-01-01
    • 1970-01-01
    • 2014-01-16
    • 2014-04-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多