开发者

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

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


The values available in the combobox can be accessed via items property

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


the best way to set the value of a datagridViewComboBoxCell is:

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


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.

Setting the index of the DataGridViewComboBox is the solution I have been looking for.....THANKS!!!

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,
all that anyone really needs is:
1. Establish the event method to be used for the "EditingControlShowing" event.
2. Define the method whereby it will:
    a. Cast the event control to a ComboBox.
    b. set the "SelectedIndex" to the value you want.
        In this example I simply set it to "0", but you'd probably want to apply so real life logic here.

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:

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


I've had some real trouble with ComboBoxes in DataGridViews and did not find an elegant way to select the first value. 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. 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

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). Hope that will save the search for some others ;)


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.

 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. 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.

      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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜