简体   繁体   English

如何在 DataGridViewComboBoxColumn 中设置 SelectedIndex?

[英]how to set SelectedIndex in DataGridViewComboBoxColumn?

i am using a datagridview in that i am using a datagridviewcomboboxcolumn, comboboxcolumn is displaying text but the problem is i want to select the first item of comboboxcolumn by default how can i do this我正在使用 datagridview,因为我正在使用 datagridviewcomboboxcolumn,comboboxcolumn 正在显示文本,但问题是我想要 select 默认情况下 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++;
}

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

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

If I had known about doing it in this event, it would have saved me days of digging and 如果我知道在这个事件中这样做,它将节省我几天的挖掘和
trial and errors trying to get it to set to the correct index inside the CellEnter event. 尝试将其设置为CellEnter事件内的正确索引的试验和错误。

Setting the index of the DataGridViewComboBox is the solution I have been looking for.....THANKS!!! 设置DataGridViewComboBox的索引是我一直在寻找的解决方案.....谢谢!

In reviewing all the issues other coders have been experiencing with trying to set 在审查其他编码员尝试设置时遇到的所有问题
the index inside of a DataGridViewComboBoxCell and also after looking over your code, DataGridViewComboBoxCell内部的索引以及查看代码之后,
all that anyone really needs is: 所有人真正需要的是:
1. Establish the event method to be used for the "EditingControlShowing" event. 1.建立用于“EditingControlShowing”事件的事件方法。
2. Define the method whereby it will: 2.定义以下方法:
a. 一个。 Cast the event control to a ComboBox. 将事件控件转换为ComboBox。
b. set the "SelectedIndex" to the value you want. 将“SelectedIndex”设置为您想要的值。
In this example I simply set it to "0", but you'd probably want to apply so real life logic here. 在这个例子中,我只是将它设置为“0”,但你可能想在这里应用如此真实的逻辑。

Here's the code I used: 这是我使用的代码:

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;
   }
}

If DataGridViewComboBoxCell already exist: 如果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;
};

the best way to set the value of a datagridViewComboBoxCell is: 设置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();
}

It worked with me very well 它非常适合我

You need to set the Items for the new cell. 您需要为新单元格设置项目。 This must be auto done by the column when creating a new row from the UI. 从UI创建新行时,必须由列自动完成此操作。

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

something different worked for me what i did is to simply set the value of dtataGridComboBox when ever new record is added bu user with 'userAddedRow' event. 不同的东西对我来说,我做的是简单地设置dtataGridComboBox的值,当有新的记录添加到用户'userAddedRow'事件。 For the first row I used the code in constructor. 对于第一行,我在构造函数中使用了代码。

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";
    }


}

Here the solution I have found: select the cell you are interested in so you can cast it to a combobox.在这里,我找到了解决方案:select 您感兴趣的单元格,因此您可以将其转换为 combobox。

      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;
      });

I've had some real trouble with ComboBoxes in DataGridViews and did not find an elegant way to select the first value. 我在DataGridViews中遇到了一些真正的ComboBox问题,并没有找到一种优雅的方法来选择第一个值。 However, here is what I ended up with: 然而,这是我最终得到的:

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);
        }
    }
}

It basically sets the .Display and .ValueMember properties of the DataGridViewComboBoxCell and uses a List as DataSource. 它基本上设置了DataGridViewComboBoxCell的.Display和.ValueMember属性,并使用List作为DataSource。 It then takes the first item, and uses reflection to get the value of the member that was used as ValueMember and sets the selected value via .Value 然后它接受第一个项目,并使用反射来获取用作ValueMember的成员的值,并通过.Value设置所选值。

Use it like this: 像这样使用它:

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");
        }
    }
}
}

It seems pretty hacky to me, but I couldn't find any better way so far (that also works with complex objects other than just Strings). 对我来说这看起来很漂亮,但到目前为止我找不到任何更好的方法(这也适用于除了Strings之外的复杂对象)。 Hope that will save the search for some others ;) 希望能省去其他人的搜索;)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM