show Yes/NO instead True/False in datagridview

后端 未结 5 542
余生分开走
余生分开走 2020-11-30 11:58

There is datagridview in a form that shows content of table of database, one column of table type is boolean, so in datagridview shows true/false, but i want to customize i

5条回答
  •  甜味超标
    2020-11-30 12:16

    If you swap the column out for a DataGridViewComboBoxColumn that is bound to a list/datatable having bool and string columns then it will decode the bool to whatever string you want (and the user can edit the values, but cannot put bad values in)

            //your datatable has some boolean column and your DataGridView is bound to it
            DataTable dt = new DataTable();
            dt.Columns.Add("MyBoolColumn", typeof(bool));     //this is your bool column
            dataGridView1.DataSource = dt;
    
    
            //make a datatable that has 2 columns, string and bool, and 2 rows (one for true, one for false)
            DataTable dv = new DataTable();
            dv.Columns.Add("Dis");                  //it will be shown in the combo
            dv.Columns.Add("Val", typeof(bool));    //it will be used by the combo to set MyBoolColumn 
            dv.Rows.Add("Yeah baby", true);
            dv.Rows.Add("Nooo way", false);
    
    
            //make a combo box column bound to the values table above 
            //and connected to the table you show in the grid
    
            var dgvcbc = new DataGridViewComboBoxColumn();
            dgvcbc.DataPropertyName = "MyBoolColumn";          //connect to the grid table
            dgvcbc.DisplayMember = "Disp";                     //show this column
            dgvcbc.ValueMember = "Val";                        //use values from this
            dgvcbc.DataSource = dv;
            dataGridView1.Columns.Add(dgvcbc);
    

    This grid will now show a combo where it once showed a checkbox, and editing the combo will change the boolean value

    You don't have to bind the combo column to a datatable. Maybe you'd prefer a list of Tuple or ValueTuple as the backing data store for the Yes/No combo:

            var dv2 = new List>() {
                new Tuple("Yeah baby", true),
                new Tuple("Noooo way", false)
            };
            var dgvcbc2 = new DataGridViewComboBoxColumn();
            dgvcbc2.DataPropertyName = "MyBoolColumn";
            dgvcbc2.DisplayMember = "Item1";                //the string in the Tuple
            dgvcbc2.ValueMember = "Item2";                  //the bool in the Tuple
            dgvcbc2.DataSource = dv2;
    
            dataGridView1.Columns.Add(dgvcbc2);
    

    If your datagridview is designed in the forms designer, the easiest thing would probably be to add a DispVal table to a strongly typed dataset, then it becomes available as a "project list instance" in the picker that lets you choose the datasource for the combo column

提交回复
热议问题