简体   繁体   中英

Set default value for DataGridView ComboBox

My application consist of DataGridviewComboBoxColumn inside DataGridView . The ComboBoxColumn s are getting filled from a database table (key, value pair). I am trying to set the default value for ComboBox column using DefaultValuesNeeded event but it is not working.

Following is the sample code:

e.Row.Cells["Job"] as DataGridViewComboBoxColumn).Value ="12"

But it shows 12 as value , instead of 12 it suppose to show actual text of 12 value.

For example:

在此处输入图片说明

DataGridViewComboBoxColumn dgvCbJob = new DataGridViewComboBoxColumn();
{
    dgvCbJob.HeaderText = "Job";
    hadd.Clear();
    hadd.Add("@Search", string.Empty);
    ds = ObjDAL.GetDataSetForPrc("prc_GetJobList", hadd);
    if (ds.Tables[0].Rows.Count > 0)
    {
        dgvCbJob.DataSource = ds.Tables[0];
        dgvCbJob.DisplayMember = "JobName";
        dgvCbJob.ValueMember = "JobMasterId";
    }
    dgvCbJob.DisplayIndex = 0;
    dgvCbJob.Width = 100;
    dgvCbJob.Name = "Job";
}

To set default value for cell you can use either of these options:

  • Handle DefaultValuesNeeded event of grid and assign value to e.Row.Cells["Job"].Value
  • In your DataTable set the DefaultValue for the 'Job' DataColumn to desired value

In both options, the type of value which you assign should be the same type as DataType of the column.

Note: You should know e.Row.Cells["Job"] is not DataGridViewComboBoxColumn . If the column is combo box, then the cell is DataGridViewComboBoxCell .

In many instances this can be done in design mode, right click dgv, select the combobox column, default cell style, Data "nullValue"

Great for simpler situations like a simple choice ABC for the user, to default to A, if you later compare with the cell's value being A or B or C, it will work. It would be a problem if you compare with the selected index however, as it counts as a value out of the collection i believe

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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