This is a migrated thread and some comments may be shown as answers.

Gridview custom add new record with default values

11 Answers 483 Views
GridView
This is a migrated thread and some comments may be shown as answers.
Andrew
Top achievements
Rank 1
Andrew asked on 28 Mar 2014, 01:25 PM
I have a form with a grid view which I have bound to a dataset (MS SQL database).  The table that I am binding to has a couple fields that have default values when adding new records.  I have figured out how to populate default values using the DefaultValuesNeeded event of the gridview control.  However this event only seems to fire if the user clicks the (click here to add new row) button at the bottom of the gridview.  I am trying to use a radButton to call a procedure to delete the row rather than use the default button at the bottom of the gridview.  I have tried using both the Add() and AddNew() functions of the gridview.  The Add() function will not work since my gridview is bound to a datasource.  The AddNew() will create a new row but it bypasses the DefaultValuesNeeded event.  I tried the code below but it didn't work - it errors out trying to set the first default value saying that no default value is specified for the second field:

Dim rowInfo As GridViewRowInfo = radGridInventoryRuns.Rows.AddNew()
rowInfo.Cells("RunYear").Value = Year(Now())
rowInfo.Cells("DateCreated").Value = Now()

 Is there anyway to mimic the behaviour of the button at the bottom of the gridview without actually clicking it.  I am using VS 2012 (vb.net) and the Q1 2014 version of the Telerik controls.

11 Answers, 1 is accepted

Sort by
0
Dess | Tech Support Engineer, Principal
Telerik team
answered on 02 Apr 2014, 08:31 AM
Hello Andrew,

Thank you for writing.

The DefaultValuesNeeded event fires when the user enters the row for new records only, so that it can be populated with default values. In order to achieve similar functionality for the data rows as well, not only for the new rows, it is appropriate to use the CellEditorInitialized event and initialize the editor's value with  the desired default value: 
//initialize default values for the new row
private void radGridView1_DefaultValuesNeeded(object sender, GridViewRowEventArgs e)
{
    e.Row.Cells["ContactName"].Value = "Default name";
    e.Row.Cells["CustomerID"].Value = Guid.NewGuid().ToString().Substring(0,5);
    e.Row.Cells["CompanyName"].Value = Guid.NewGuid().ToString().Substring(0,5);
}
 
//initialize default values for the data row
private void radGridView1_CellEditorInitialized(object sender, GridViewCellEventArgs e)
{
    if (e.Row is GridViewDataRowInfo)
    {
        if (e.Column.Name=="ContactName")
        {
            e.ActiveEditor.Value = "Default Value";
        }
    }
}

I hope this information helps. Should you have further questions, I would be glad to help.

Regards,
Desislava
Telerik

Check out the Telerik Platform - the only platform that combines a rich set of UI tools with powerful cloud services to develop web, hybrid and native mobile apps.

 
0
Andrew
Top achievements
Rank 1
answered on 02 Apr 2014, 11:55 AM
Thanks for the response - I tried your solution and it isn't working for me.  For some reason the CellEditorInitialized event never fires.  Here is my code: (defaultValuesNeeded does not fire either)

    Private Sub cmdCreateNewInventoryRun_Click(sender As Object, e As EventArgs) Handles cmdCreateNewInventoryRun.Click

     
        radGridInventoryRuns.Rows.AddNew()


    End Sub

    'Capture this event to insert default values into the new InventoryRun row - if you call addnew in code it does not fire the DefaultValuesNeeded event 
    Private Sub radGridInventoryRuns_CellEditorInitialized(sender As Object, e As GridViewCellEventArgs) Handles radGridInventoryRuns.CellEditorInitialized

        If TypeOf e.Row Is GridViewDataRowInfo Then

            Select e.Column.Name
                Case "DateCreated"
                    e.ActiveEditor.Value = Now()
                Case "RunYear"
                    e.ActiveEditor.Value = Year(Now())
                Case "InventoryDownloaded"
                    e.ActiveEditor.Value = False
            End Select

        End If
    End Sub
0
Andrew
Top achievements
Rank 1
answered on 02 Apr 2014, 12:08 PM
Ok ... now i see how the event fires.  When you move from cell to cell on the new row it fires but there is a strange problem - as soon as I tab out of the cell with the new default value inserted it disappears! If i click back on the cell it appears again - if I hit enter to finish adding the row I get an error because the table I have the grid bound to doesn't accept null values for that column.  This seems like a rather messy and buggy workaround.  Is there no way to simply fire the same event that is fired when the user clicks on the "Click here to add new row" button that comes standard with the rad gridview?
0
Dess | Tech Support Engineer, Principal
Telerik team
answered on 07 Apr 2014, 08:43 AM
Hello Andrew,

Thank you for writing back.

The DefaultValuesNeeded event is appropriate to fill the default values for the new row and these default values will be stored in the new row. This event is purposed to handle exactly this case.

As to the data rows, when the editor is initialized, its default value is the current cell's value and it is possible to change it, but in order to store its value in the cell (when no other changes are performed), you should use the following approach. You can handle the new row with it as well:
private void radGridView1_CellEditorInitialized(object sender, GridViewCellEventArgs e)
{
    if (e.Column.Name == "ContactName")
    {
        e.ActiveEditor.Value = "Default Value";   
    }
    else if (e.Column.Name == "CustomerID" || e.Column.Name == "CompanyName")
    {
        e.ActiveEditor.Value = Guid.NewGuid().ToString().Substring(0, 5);             
    }
}
 
private void radGridView1_CellEndEdit(object sender, GridViewCellEventArgs e)
{
    if (currentValue != string.Empty && e.ActiveEditor == null &&
        currentValue != radGridView1.CurrentCell.Value
    )
    {
        radGridView1.CurrentCell.Value = currentValue;
    }
}
 
string currentValue = string.Empty;
 
private void radGridView1_CellValidating(object sender, CellValidatingEventArgs e)
{
    if (e.ActiveEditor != null && e.ActiveEditor.Value != null)
    {
        currentValue = e.ActiveEditor.Value.ToString();
    }
}

Note that this is just a sample approach and it may not cover all possible cases. Feel free to modify it on a way, which suit your requirement best.

Please do not hesitate to contact us if you have any additional questions.
  
Regards,
Desislava
Telerik
 

Check out the Telerik Platform - the only platform that combines a rich set of UI tools with powerful cloud services to develop web, hybrid and native mobile apps.

 
0
Andrew
Top achievements
Rank 1
answered on 08 Apr 2014, 01:48 PM
I'm not sure if you understood my question?  I tried your solution and as you tab across the columns you briefly see the default values appear in the currently active cell but as soon as you tab out of the cell the value is hidden. I have my code exactly like the code you posted and the CellEndEdit and CellValiddating events never fire.  When i tab off the end of the row I get an error that one of my columns cannot be null (i have a non-null constraint on the column)  - even though when i tabbed through that column i briefly saw the default value appear there.  I will post my code at the end of this post - I will convert it to C# for you.
This is not the experience that my end users want to have.  I would like to have the user click a button on the form to add a new row and see the new values pre-populated in that new row after they click the button.  Some of the columns in my gridview are Read Only to the user and that's why I want them pre-populated with default or calculated values.  It works like this if you allow the user to click the "Add New Row" at the bottom of the gridview and use the defaultvaluesneeded event - I just don't understand why you can't call that same procedure but from a button outside of the gridview?

private void cmdCreateNewInventoryRun_Click(object sender, EventArgs e)
{
    radGridInvRuns.Rows.AddNew();
 
}
 
//Capture this event to insert default values into the new InventoryRun row - if you call addnew in code it does not fire the DefaultValuesNeeded event
 
private void radGridInventoryRuns_CellEditorInitialized(object sender, GridViewCellEventArgs e)
{
 
    if (e.Row is GridViewDataRowInfo) {
        switch (e.Column.Name) {
            case "DateCreated":
                e.ActiveEditor.Value = DateAndTime.Now();
 
                break;
            case "RunYear":
                e.ActiveEditor.Value = DateAndTime.Year(DateAndTime.Now());
                break;
            case "InventoryDownloaded":
                e.ActiveEditor.Value = 0;
                break;
            case "RunClosed":
                e.ActiveEditor.Value = 0;
                break;
        }
 
    }
}
 
 
private string currentValue = string.Empty;
 
private void RadGridInventory_CellEndEdit(object sender, GridViewCellEventArgs e)
{
    if (currentValue != string.Empty && e.ActiveEditor == null && currentValue != radGridInvRuns.CurrentCell.Value) {
        radGridInvRuns.CurrentCell.Value = currentValue;
    }
 
}
 
 
private void RadGridInventory_CellValidating(object sender, CellValidatingEventArgs e)
{
    if (e.ActiveEditor != null && e.ActiveEditor.Value != null) {
        currentValue = e.ActiveEditor.Value.ToString();
    }
}




0
Andrew
Top achievements
Rank 1
answered on 09 Apr 2014, 05:51 PM
So I did find a mistake in my code and now the CellEndEdit  and CellValidating events are firing and the values are staying in the cells, however I still don't want the user to have to click on or tab through each cell to get the default values inserted.  It works perfectly when clicking the "buillt in" Add New Row button on the gridview - is there anyway to fire this event from code?
0
Dimitar
Telerik team
answered on 11 Apr 2014, 07:54 AM
Hello Andrew,

Thank you for writing back.

I have reviewed the whole thread and If I understand correctly you want to add new row with default values inserted to it upon a button click, not using the default new row behaviour. 

Another approach would be to use the Add method of the Rows collection. For the columns that you do not want to set default value you can set the value to Nothing:
Private Sub radButton1_Click(sender As Object, e As EventArgs)
    radGridView1.Rows.Add(Nothing, "Default Value1", "Default Value2", Nothing)
End Sub

Another approach is to use the AddNew method and then change the values in the CollectionChanged event of the Rows collection:
Private Sub Rows_CollectionChanged(sender As Object, e As Telerik.WinControls.Data.NotifyCollectionChangedEventArgs)
    If e.Action = NotifyCollectionChangedAction.Add Then
        Dim newRow As GridViewDataRowInfo = TryCast(e.NewItems(0), GridViewDataRowInfo)
        newRow.Cells(1).Value = "Default Value 1"
        newRow.Cells(2).Value = "Default Value 2"
    End If
End Sub

More information about this event can be found in the following article: Tracking changes in RadGridView.

I hope this helps.

Regards,
Dimitar
Telerik
 

Check out the Telerik Platform - the only platform that combines a rich set of UI tools with powerful cloud services to develop web, hybrid and native mobile apps.

 
0
Eyo
Top achievements
Rank 1
answered on 03 Feb 2018, 05:00 PM
there is no CellEditorInitialized event in gridview
0
Dimitar
Telerik team
answered on 05 Feb 2018, 07:48 AM
Hi Eyo,

I am not sure why the event is not available on your side. This is why I want to kindly ask you to open a support ticket and provide a detailed information about your case.

I am looking forward to your reply.

Regards,
Dimitar
Progress Telerik
Try our brand new, jQuery-free Angular components built from ground-up which deliver the business app essential building blocks - a grid component, data visualization (charts) and form elements.
0
Hengky
Top achievements
Rank 1
Veteran
answered on 06 Feb 2018, 07:05 AM

I have similiar problem like that 

    Private Sub TxtKodeBarang_KeyDown(sender As Object, e As KeyEventArgs) Handles TxtKodeBarang.KeyDown
        If e.KeyCode = System.Windows.Forms.Keys.Enter Then
            Using db As New MTSEntities
                Dim StrCari = db.MstBarangs.Where(Function(d) d.KodeBarang = TxtKodeBarang.Text).SingleOrDefault  'TxtKode.Text).FirstOrDefault
                If IsNothing(StrCari) Then
                    BtnCrBarang_Click(sender, e)
                Else
                    TxtKodeGudang.Text = StrCari.KodeBarang.ToString
                    LblNamaGudang.Text = StrCari.NamaBarang.ToString
                End If
            End Using
        End If
    End Sub

I need this code on radgrid_cell value changed.... how make this happen ? but not for fill the textbox but fill column1 and column2

 

 

0
Dimitar
Telerik team
answered on 06 Feb 2018, 12:09 PM
Hi Hengky,

In the CellValueChanged you can directly access the values of the current row:
Private Sub RadGridView1_CellValueChanged(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.GridViewCellEventArgs)
    If e.Column.Name = "column4" Then
        e.Row.Cells("column1").Value = "Test"
        e.Row.Cells("column2").Value = "Test"
    End If
End Sub

I hope this will be useful. 

Regards,
Dimitar
Progress Telerik
Try our brand new, jQuery-free Angular components built from ground-up which deliver the business app essential building blocks - a grid component, data visualization (charts) and form elements.
Tags
GridView
Asked by
Andrew
Top achievements
Rank 1
Answers by
Dess | Tech Support Engineer, Principal
Telerik team
Andrew
Top achievements
Rank 1
Dimitar
Telerik team
Eyo
Top achievements
Rank 1
Hengky
Top achievements
Rank 1
Veteran
Share this question
or