如何在DataGridViewComboBoxColumn中设置SelectedIndex?

10

我正在使用一个DataGridView,其中包含一个DataGridViewComboBoxColumn。ComboBoxColumn会显示文本,但是问题是我想默认选择ComboBoxColumn的第一个项目,我该怎么做?

DataGridViewComboBoxColumn dgvcb = (DataGridViewComboBoxColumn)grvPackingList.Columns["PackingUnits"];
Globals.G_ProductUtility G_Utility = new Globals.G_ProductUtility();
G_Utility.addUnittoComboDGV(dgvcb);
DataSet _ds = iRawMaterialsRequest.SelectBMR(bmr_ID, branch_ID, "PACKING");
grvPackingList.DataSource = _ds.Tables[0];
int i = 0;
foreach (DataRow dgvr in _ds.Tables[0].Rows)
{
    grvPackingList.Rows[i].Cells["Units"].Value = dgvr["Units"].ToString();
    i++;
}
8个回答

18

可以通过items属性访问组合框中可用的值。

row.Cells[col.Name].Value = (row.Cells[col.Name] as DataGridViewComboBoxCell).Items[0];

2
我想在GridView中的ComboBox中默认选择文本,但这里不起作用。 - Nighil
循环遍历行并在网格的DataBindingComplete事件中进行设置。 - V4Vendetta
@V4Vendetta,你能帮忙提供“DataBindingComplete事件”的示例代码吗? - Smith

2

如果我早知道在这个事件中这样做,就可以节省我数天的挖掘和试错,尝试将其设置为正确的索引。

设置DataGridViewComboBox的索引是我一直在寻找的解决方案.....谢谢!!!

在审查其他编码人员尝试设置DataGridViewComboBoxCell中的索引时遇到的所有问题并查看您的代码后,任何人都需要的只有:
1.建立要用于“EditingControlShowing”事件的事件方法。
2.定义它将如何:
    a.将事件控件转换为ComboBox。
    b.将“SelectedIndex”设置为所需值。
        在此示例中,我只是将其设置为“0”,但您可能想在此应用实际逻辑。

这是我使用的代码:

private void InitEvents()
{

    dgv4.EditingControlShowing += new DataGridViewEditingControlShowingEventHandler( dgv4EditingControlShowing );

}


private void dgv4EditingControlShowing( object sender, DataGridViewEditingControlShowingEventArgs e )
{
   ComboBox ocmb = e.Control as ComboBox;
   if ( ocmb != null )
   {
      ocmb.SelectedIndex = 0;
   }
}

1
EditingControlShowing只在编辑模式下触发,因此这不是一个有效的解决方案。 - MC9000

2

设置DataGridViewComboBoxCell的最佳方法是:

DataTable dt = new DataTable();
dt.Columns.Add("Item");
dt.Columns.Add("Value");
dt.Rows.Add("Item1", "0");
dt.Rows.Add("Item1", "1");
dt.Rows.Add("Item1", "2");
dt.Rows.Add("Item1", "3");
DataGridViewComboBoxColumn cmb = new DataGridViewComboBoxColumn();
cmb.DefaultCellStyle.Font = new Font("Tahoma", 8, FontStyle.Bold);
cmb.DefaultCellStyle.ForeColor = Color.BlueViolet;
cmb.FlatStyle = FlatStyle.Flat;
cmb.Name = "ComboColumnSample";
cmb.HeaderText = "ComboColumnSample";
cmb.DisplayMember = "Item";
cmb.ValueMember = "Value";
DatagridView dvg=new DataGridView();
dvg.Columns.Add(cmb);
cmb.DataSource = dt;
for (int i = 0; i < dvg.Rows.Count; i++)
{
dvg.Rows[i].Cells["ComboColumnSample"].Value = (cmb.Items[0] as 
DataRowView).Row[1].ToString();
}

它对我非常有效。


1
如果 DataGridViewComboBoxCell 已经存在:
DataTable dt = new DataTable();
dt.Columns.Add("Item");
dt.Columns.Add("Value");
dt.Rows.Add("Item 1", "0");
dt.Rows.Add("Item 2", "1");
dt.Rows.Add("Item 3", "2");
dt.Rows.Add("Item 4", "3");

for (int i = 0; i < dvg.Rows.Count; i++)
{
    DataGridViewComboBoxCell comboCell = (DataGridViewComboBoxCell)dvg.Rows[i].Cells[1];
    comboCell.DisplayMember = "Item";
    comboCell.ValueMember = "Value";
    comboCell.DataSource = dt;
};

0

这里是我找到的解决方案:选择您感兴趣的单元格,以便将其转换为组合框。

      this.Invoke((MethodInvoker)delegate
      {
        this.dataGridView1.CurrentCell = dataGridView1.Rows[yourRowindex].Cells[yourColumnIndex];
        this.dataGridView1.BeginEdit(true);
        ComboBox comboBox = (ComboBox)this.dataGridView1.EditingControl;
        comboBox.SelectedIndex += 1;
      });

0

对我而言,有所不同的是我在用户使用“userAddedRow”事件添加新记录时,仅仅设置了dtataGridComboBox的值。对于第一行,我在构造函数中使用了代码。

public partial class pt_drug : PatientDatabase1_3._5.basic_templet
{
    public pt_drug()
    {
        InitializeComponent();
        dataGridView_drugsDM.Rows[0].Cells[0].Value = "Tablet";
    }

    private void dataGridView_drugsDM_UserAddedRow(object sender, DataGridViewRowEventArgs e)
    {
        dataGridView_drugsDM.Rows[dataGridView_drugsDM.RowCount - 1].Cells[0].Value = "Tablet";
    }


}

0

您需要为新单元格设置项目。当从UI创建新行时,列必须自动完成此操作。

 var cell = new DataGridViewComboBoxCell() { Value = "SomeText" };
 cell.Items.AddRange(new String[]{"SomeText", "Abcd", "123"});

0
我在DataGridView中使用ComboBox遇到了一些麻烦,并没有找到一种优雅的方式来选择第一个值。然而,这是我最终选择的方法:
public static void InitDGVComboBoxColumn<T>(DataGridViewComboBoxCell cbx, List<T> dataSource, String displayMember, String valueMember)
{
    cbx.DisplayMember = displayMember;
    cbx.ValueMember = valueMember;
    cbx.DataSource = dataSource;
    if (cbx.Value == null)
    {
        if(dataSource.Count > 0)
        {
            T m = (T)cbx.Items[0];
            FieldInfo fi = m.GetType().GetField(valueMember, BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public);
            cbx.Value = fi.GetValue(m);
        }
    }
}

它基本上设置了DataGridViewComboBoxCell的.Display和.ValueMember属性,并使用List作为数据源。然后,它获取第一个项目,并使用反射来获取用作ValueMember的成员的值,并通过.Value设置所选值。

像这样使用:

public class Customer
{
    private String name;
    public String Name
    {
        get {return this.name; }
        set {this.name = value; }
    }

    private int id;
    public int Id
    {
        get {return this.id; }
        set {this.id = value; }
    }
}

public class CustomerCbx
{
    private String display;
    public String Display
    {
        get {return this.display; }
        set {this.display = value; }
    }

    private Customer value;
    public Customer Value
    {
        get {return this.value; }
        set {this.value = value; }
    }
}

public class Form{
private void Form_OnLoad(object sender, EventArgs e)
{
        //init first row in the dgv
        if (this.dgv.RowCount > 0)
        {
            DataGridViewRow row = this.dgv.Rows[0];
            DataGridViewComboBoxCell cbx = (DataGridViewComboBoxCell)row.Cells[0];

            Customer c1 = new Customer(){ Name = "Max Muster", ID=1 };
            Customer c2 = new Customer(){ Name = "Peter Parker", ID=2 };
            List<CustomerCbx> custList = new List<CustomerCbx>()
            {
                new CustomerCbx{ Display = c1.Name, Value = c1},
                new CustomerCbx{ Display = c2.Name, Value = c2},
            }

            InitDGVComboBoxColumn<CustomerCbx>(cbx, custList, "display", "value");
        }
    }
}
}

对我来说,这似乎是一种相当hacky的方法,但迄今为止我找不到更好的方法(也适用于复杂对象而不仅仅是字符串)。希望这能为其他人节省搜索时间;)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接