运行时禁用datagridviewcombobox

时间:2011-03-21 03:30:54

标签: c# winforms

如何在运行时更改DataGridViewComboBoxColumn的以下内容:

  1. 如何将组合框的第一个值设置为默认值?
  2. 禁用组合框/将其设为只读,同时将第一个值显示为默认值。意思是说,如果我在组合框中有3个项目,它应该只显示第一个项目。 (禁用组合框下拉,或将其更改为运行时的文本框)。
  3. 原因:
    我这样做的原因是因为Enum我有Status{New=1,Stop=2,Temp=3}。当我想注册学生时,状态始终设置为New。因此,当我保存时,它会自动保存Status = 1

2 个答案:

答案 0 :(得分:9)

以下是设置默认值并禁用单元格的方法:

using System;
using System.Windows.Forms;

namespace WindowsFormsApplication3
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            Column1.DataSource = new int[] { 1, 2, 3 };
            Column1.DataPropertyName = "Number";
            dataGridView1.DataSource = new[] 
            { 
                new { Number=1 },
                new { Number=2 },
                new { Number=3 },
                new { Number=1 }
            };
        }

        private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (e.ColumnIndex == Column1.Index && e.RowIndex == (dataGridView1.Rows.Count - 1))
            {
                DataGridViewComboBoxCell cell = (DataGridViewComboBoxCell)dataGridView1[e.ColumnIndex, e.RowIndex];

                cell.Value = 2;
                cell.DisplayStyle = DataGridViewComboBoxDisplayStyle.Nothing;
                cell.ReadOnly = true;
            }
        }
    }
}

答案 1 :(得分:0)

根据这些文章,DataGridView组合框控件有SelectedIndex:

http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.editingcontrolshowing.aspx

http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridviewcomboboxeditingcontrol(v=vs.80).aspx

[1]。我就是这样做的:

private void dgv_EditingControlShowing(object sender, System.Windows.Forms.DataGridViewEditingControlShowingEventArgs e)
{
if (e.Control is DataGridViewComboBoxEditingControl) {


    DataGridViewComboBoxEditingControl control = e.Control as DataGridViewComboBoxEditingControl;


    BindingSource bs = control.DataSource as BindingSource;
    if (!IsNothing(bs)) {

        // set the filteredChildBS as the DataSource of the editing control
         ((ComboBox)e.Control).DataSource = filteredChildBS;

        //Set the dgv's combobox to the first item
         ((ComboBox)e.Control).SelectedIndex = 1

    }
}

}

filtereredChildBS是一个绑定源,如果您需要澄清,请告诉我?

[2]。禁用datagridview控制它有点棘手。我使用此示例禁用DataGridView复选框:http://social.msdn.microsoft.com/forums/en-US/winformsdatacontrols/thread/988c7e3f-c172-467d-89b7-b80a60b7f24f/但对于组合框,更简单的方法是禁用列带:

foreach (DataGridViewBand band in dgvTransactions.Columns)  { if (i !=7) band.ReadOnly = (bool)i == 0;       i+= 1;  band.Frozen = false;  }

如果您需要进一步澄清,请告诉我?