使用C#在DataGrid视图中更新时替换数据

时间:2018-12-16 13:20:11

标签: c# mysql .net winforms datagridview

enter image description here

从数据库上方的图像0和1上方,同时在数据网格视图1中显示的值由高替换为0,由低替换替换为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();

1 个答案:

答案 0 :(得分:3)

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

  • 使用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

另一个选择是使用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;

enter image description here