1.11M Members

Set default value for column in datagridview

 
0
 

I want to set default value for column of datagridview.I am adding combobox column "caste" at runtime in datagridview.Now while adding each row,if database have value for caste field,combobox should show that value as default value else no default value should be selected.Thanks in advance.

 
0
 

Try something like an IIF statement:

Col1 = IIF(IsDBNull(ds.Tables("myTable").Rows(intCurRow)("Caste")),"MY DEFAULT VALUE HERE",ds.Tables("myTable").Rows(intCurRow)("Caste"))
 
0
 

Now while adding each row,if database have value for caste field,combobox should show that value as default value else no default value should be selected.Thanks in advance.

So if the database value is null (no value set), you want the combobox to reflect this by not selecting one of the values in it's Items list?

In my experience, the datagridview combobox cell behaves this way already if the cell value is null (DBNull.Value). Just set the cell value to the value from your database and it should work. Just make sure that all valid values are defined in the column's Items list or you will get a "DataError". The DBNull.Value should not be added to this list.

Are the rest of the datagridview columns bound to a datasource filled from the same database that "caste" is pulled from? If so, there is no need to add
the additional column. Just include "caste" in the bound colums and change it's celltype in the RowsAdded event handler.

   Private Sub dgv_RowsAdded(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewRowsAddedEventArgs) Handles dgv.RowsAdded
      ' Loop through the added rows and change the cell to a DataGridViewComboBoxCell
      For i As Int32 = e.RowIndex To (e.RowIndex + e.RowCount - 1)
         dgv.Rows(i).Cells(dgvComboBoxCellName) = _
            New DataGridViewComboBoxCell With {.Value = dgv.Rows(i).Cells(dgvComboBoxCellName).Value, _
                                               .DataSource = dgvComboBoxItems}
      Next i
   End Sub
 
0
 

Yes caste is coming from same table(datafile) but ID is stored which has corresponding description in another table.And if caste value is not null in datafile,then Description for that ID should be displayed in comboboxcolumn.

You
This article has been dead for over six months: Start a new discussion instead
Post:
Start New Discussion
Tags Related to this Article