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

[Solved] Please help adding/deleting a record...

9 Answers 210 Views
GridView
This is a migrated thread and some comments may be shown as answers.
This question is locked. New answers and comments are not allowed.
Joshua
Top achievements
Rank 1
Joshua asked on 21 Aug 2010, 05:50 PM

First off, I been programming in .NET for a few years, but I just started w/ Silverlight this past week, so please keep your answers straight forward and don't assume anything. Thanks...

I have the following web service...

MyApp.svc.cs

namespace MyApp.Web
{
    #region Data Types
    [DataContract]
    public class Record : INotifyPropertyChanged
    {
        private Guid _RecordID;
        private string _RecordName;
        private Boolean _Active;
  
        [DataMember]
        public Guid RecordID
        {
            get { return _RecordID; }
            set
                _RecordID = value;
                OnPropertyChanged("RecordID");
            }
        }
  
        [DataMember]
        public string RecordName
        {
            get { return _RecordName; }
            set
                _RecordName = value;
                OnPropertyChanged("RecordName");
            }
        }
  
        [DataMember]
        public Boolean Active
        {
            get { return _Active; }
            set
                _Active = value;
                OnPropertyChanged("Active");
            }
        }
  
         
        public event PropertyChangedEventHandler PropertyChanged;
          
        public void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this,
                new PropertyChangedEventArgs(propertyName));
            }
        }
    }
  
    #endregion
  
  
    #region Classes
  
    [ServiceContract(Namespace = "")]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class MyApp
    {
        [OperationContract]
        public List<Record> GetRecords()
        {
            return SampleRecords.Instance().GetRecords();
        }
  
        [OperationContract]
        public Guid AddRecord(Record record)
        {
            return SampleRecords.Instance().AddRecord(record);
        }
          
    }
  
    #endregion
}


SampleRecords class:


namespace MyApp.Web
{
    public class SampleRecords
    {
        public static SampleRecords Instance()
        {
            return (SampleRecords)Activator.CreateInstance(typeof(SampleRecords));
        }
  
        public List<Record> GetRecords()
        {
            List<Record> records = new List<Record>();
            Record record;
  
            try
            {
                using (SqlDataReader reader = SqlHelper.ExecuteReader(Globals.ConnectionString, "GetRecords"))
                {
                    while (reader.Read())
                    {
                        record = new Record();
                        record.RecordID = (Guid)reader["RecordID"];
                        record.RecordName = reader["Record"].ToString();
                        record.Active = Convert.ToBoolean(reader["Active"]);
                        records.Add(record);
                    }
                }
            }
            catch { }
  
            return records;
        }
  
        public Guid AddRecord(Record record)
        {
            return (Guid)SqlHelper.ExecuteScalar(Globals.ConnectionString, "AddRecord", record.RecordName, record.Active);
        }
    }
}



MainPage.xaml.cs (there's a RadGridView on the control - "rgvRecords"):


namespace SampleRecords
{
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();
  
            MyAppClient proxy = new MyAppClient();
            proxy.GetRecordsCompleted += new EventHandler<GetRecordsCompletedEventArgs>(proxy_GetRecordsCompleted);
            proxy.GetRecordsAsync();
              
        }
  
        void proxy_GetRecordsCompleted(object sender, GetRecordsCompletedEventArgs e)
        {
              
            try
            {
                rgvRecords.ItemsSource = e.Result;
            }
            catch { }
              
        }
    }
}


As you can see, I've pretty much got the guts of this done, but I guess my question is, Where do I call proxy.AddRecordAsync (and eventually proxy.DeleteRecordAsync)?  Also, how does this all work with INotifyPropertyChanged?

Correct me if I'm wrong, but I'm assuming I use the AddingNewDataItem and call proxy.AddRecordAsync(record)?  But then my question is, the AddRecord SQL stored procedure returns SCOPE_IDENTITY().  Does the returned identifier automatically get assigned to the new record in the RadGridView, or do I have to update it manually?

Like I said, I'm sure these are pretty basic questions, but I'm really having a hard time getting my head around the MVVM at the moment.

Thanks so much.
Joshua

9 Answers, 1 is accepted

Sort by
0
Joshua
Top achievements
Rank 1
answered on 21 Aug 2010, 07:29 PM
Okay so I've got this for inserting a record, but I have one other question... (please see after code)

private void rgvRecordss_RowEditEnded(object sender, Telerik.Windows.Controls.GridViewRowEditEndedEventArgs e)
{
    if (e.EditAction == Telerik.Windows.Controls.GridView.GridViewEditAction.Commit)
    {
        if (e.EditOperationType == Telerik.Windows.Controls.GridView.GridViewEditOperationType.Insert)
        {
            Record record = e.EditedItem as Record;
            MyAppClient proxy = new MyAppClient();
            proxy.AddRecordCompleted += new EventHandler<AddRecordCompletedEventArgs>(proxy_AddRecordCompleted);
            proxy.AddRecordAsync(league);
        }
    }
}
void proxy_AddRecordCompleted(object sender, AddRecordCompletedEventArgs e)
{
    //((Record)rgvRecords.CurrentItem).RecordID = e.Result;
}


The e.Result of AddRecordCompleted returns a GUID.  How do I set it to the Guid of the record I just added?  Because currently, the RadGrid just shows zeros in the RecordID column.  Do I have to call Rebind()?  That kind of defeats the purpose of the ObservableCollection doesn't it?

Thanks.
0
Joshua
Top achievements
Rank 1
answered on 21 Aug 2010, 10:34 PM
Okay here's what I ended up with. If anyone has any suggestions, I'm open, but please remember to keep them simple regarding the MVVM.  I, of course, want to learn good coding standards.

MyApp Services Code-behind:

namespace MyApp.Web
{
    #region Data Types
    [DataContract]
    public class Record : INotifyPropertyChanged
    {
        private Guid _RecordID;
        private string _RecordName;
        private Boolean _Active;
  
        [DataMember]
        public Guid RecordID
        {
            get { return _RecordID; }
            set
                _RecordID = value;
                OnPropertyChanged("RecordID");
            }
        }
  
        [DataMember]
        public string RecordName
        {
            get { return _RecordName; }
            set
                _RecordName = value;
                OnPropertyChanged("RecordName");
            }
        }
  
        [DataMember]
        public Boolean Active
        {
            get { return _Active; }
            set
                _Active = value;
                OnPropertyChanged("Active");
            }
        }
  
         
        public event PropertyChangedEventHandler PropertyChanged;
  
        protected virtual void OnPropertyChanged(PropertyChangedEventArgs args)
        {
            PropertyChangedEventHandler handler = this.PropertyChanged;
            if (handler != null)
            {
                handler(this, args);
            }
        }
  
        private void OnPropertyChanged(string propertyName)
        {
            this.OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
        }
    }
  
    #endregion
  
  
    #region Classes
  
    [ServiceContract(Namespace = "")]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class MyApp
    {
        [OperationContract]
        public ObservableCollection<Record> GetRecords()
        {
            return SampleRecords.Instance().GetRecords();
        }
  
        [OperationContract]
        public Guid AddRecord(Record record)
        {
            return SampleRecords.Instance().AddRecord(record);
        }
          
    }
  
    #endregion
}


SampleRecords class:

namespace MyApp.Web
{
    public class SampleRecords
    {
        public static SampleRecords Instance()
        {
            return (SampleRecords)Activator.CreateInstance(typeof(SampleRecords));
        }
  
        public ObservableCollection<Record> GetRecords()
        {
            ObservableCollection<Record> records = new ObservableCollection<Record>();
            Record record;
  
            try
            {
                using (SqlDataReader reader = SqlHelper.ExecuteReader(Globals.ConnectionString, "GetRecords"))
                {
                    while (reader.Read())
                    {
                        record = new Record();
                        record.RecordID = (Guid)reader["RecordID"];
                        record.RecordName = reader["Record"].ToString();
                        record.Active = Convert.ToBoolean(reader["Active"]);
                        record.Add(record);
                    }
                }
            }
            catch { }
  
            return records;
        }
  
        public Guid AddRecord(Record record)
        {
            return (Guid)SqlHelper.ExecuteScalar(Globals.ConnectionString, "AddRecord", record.RecordName, record.Active);
        }
    }
}


MainPage.xaml.cs

namespace SampleRecords
{
    public partial class MainPage : UserControl
    {
        private Record _record;
  
        public MainPage()
        {
            InitializeComponent();
  
            MyAppClient proxy = new MyAppClient();
            proxy.GetRecordsCompleted += new EventHandler<GetRecordsCompletedEventArgs>(proxy_GetRecordsCompleted);
            proxy.GetRecordsAsync();
        }
  
        void proxy_GetRecordsCompleted(object sender, GetRecordsCompletedEventArgs e)
        {
              
            try
            {
                rgvRecords.ItemsSource = e.Result;
            }
            catch { }
              
        }
  
        private void rgvRecords_RowEditEnded(object sender, Telerik.Windows.Controls.GridViewRowEditEndedEventArgs e)
        {
            _record = e.EditedItem as Record;
  
            if (e.EditAction == Telerik.Windows.Controls.GridView.GridViewEditAction.Commit)
            {
                if (e.EditOperationType == Telerik.Windows.Controls.GridView.GridViewEditOperationType.Insert)
                {
                    MyAppClient proxy = new MyAppClient();
                    proxy.AddRecordCompleted += new EventHandler<AddRecordCompletedEventArgs>(proxy_AddRecordCompleted);
                    proxy.AddRecordAsync(_record);
                   
                    rgvRecords.Items.CommitNew();
                }
                else if (e.EditOperationType == Telerik.Windows.Controls.GridView.GridViewEditOperationType.Edit)
                {
                    // Update record code goes here
                      
                    rgvRecords.Items.CommitEdit();
                }
            }
  
        }
  
        void proxy_AddRecordCompleted(object sender, AddRecordCompletedEventArgs e)
        {
            _record.RecordID = e.Result;
        }
  
        private void rgvRecords_CellValidating(object sender, Telerik.Windows.Controls.GridViewCellValidatingEventArgs e)
        {
            if (e.Cell.Column.UniqueName.Equals("RecordName"))
                e.IsValid = !string.IsNullOrWhiteSpace(e.NewValue.ToString());
              
        }
  
    }
}
0
Yavor Georgiev
Telerik team
answered on 23 Aug 2010, 12:19 PM
Hi Joshua,

 I think it would be far easier for you if you used WCF RIA Services. That way the system will automatically handle CRUD operations and similar for you. If you like, I can even prepare a very simple solution to illustrate how RIA Services work with our RadGridView. If, however, using regular WCF is a requirement for you, please let us know, and we will try to refine your implementation of your scenario as best as we can.

Kind regards,
Yavor Georgiev
the Telerik team
Do you want to have your say when we set our development plans? Do you want to know when a feature you care about is added or when a bug fixed? Explore the Telerik Public Issue Tracking system and vote to affect the priority of the items
0
Joshua
Top achievements
Rank 1
answered on 23 Aug 2010, 08:17 PM
Yavor,

First, the link you provided shines a LOT more light on the subject; I greatly appreciate it.

If you don't mind, could you create a simple solution for illustration purposes, especially an example that incorporates the Add Record Row and a delete button on each row.

Thanks so much!

Joshua
0
Yavor Georgiev
Telerik team
answered on 24 Aug 2010, 10:59 AM
Hello Joshua,

 Please find attached a sample solution.

The Entity model is generated against the sample AdventureWorks database, which you can find here. You may have to tweak your connection string to connect to your local copy.

Best wishes,
Yavor Georgiev
the Telerik team
Do you want to have your say when we set our development plans? Do you want to know when a feature you care about is added or when a bug fixed? Explore the Telerik Public Issue Tracking system and vote to affect the priority of the items
0
Joshua
Top achievements
Rank 1
answered on 24 Aug 2010, 02:31 PM
Yavor,

I see you have a RadButton for the Delete Command and RadButton at the bottom to SubmitChanges.

Is there a way for me to make the Delete instantaneous instead of having to click two buttons?  Should I hook into the Click event of the Delete button or another event, such as Deleted, of the Grid?  What's the best way to do it?

Thanks so much for your help.

Joshua
0
Yavor Georgiev
Telerik team
answered on 24 Aug 2010, 02:34 PM
Hi Joshua,

 You can handle the Deleted and RowEditEnded events of RadGridView so that you can call the SubmitChanges method of the DomainDataSource object whenever a row is deleted, inserted or changed.

Regards,
Yavor Georgiev
the Telerik team
Do you want to have your say when we set our development plans? Do you want to know when a feature you care about is added or when a bug fixed? Explore the Telerik Public Issue Tracking system and vote to affect the priority of the items
0
Joshua
Top achievements
Rank 1
answered on 24 Aug 2010, 07:53 PM
Yavor,

Here's my XAML:

<Grid x:Name="RecordsGrid">
    <riaControls:DomainDataSource AutoLoad="True" d:DesignData="{d:DesignInstance MyApp:Record, CreateList=True}" Height="0" LoadedData="recordsDomainDataSource_LoadedData" Name="recordsDomainDataSource" QueryName="GetRecords" Width="0">
        <riaControls:DomainDataSource.DomainContext>
            <MyApp:MyAppContext />
        </riaControls:DomainDataSource.DomainContext>
    </riaControls:DomainDataSource>
    <telerik:RadGridView HorizontalAlignment="Left" Name="rgvRecords" 
                        VerticalAlignment="Top" ShowGroupPanel="False" 
                        RowIndicatorVisibility="Collapsed"
                        CanUserDeleteRows="True" 
                        ShowInsertRow="True" 
                        CanUserReorderColumns="False" 
                        CanUserSelect="False" 
                        CanUserResizeColumns="False" 
                        AutoGenerateColumns="False" 
                        CanUserFreezeColumns="False"
                        ItemsSource="{Binding ElementName=recordsDomainDataSource, Path=Data}"
                        IsBusy="{Binding IsBusy, ElementName=recordsDomainDataSource}"
                        Deleted="rgvRecords_Deleted"
                        RowEditEnded="rgvRecords_RowEditEnded">
        <telerik:RadGridView.Columns>
            <telerik:GridViewDataColumn Header="" Width="75" IsFilterable="False">
                <telerik:GridViewDataColumn.CellTemplate>
                    <DataTemplate>
                        <telerik:RadButton Margin="5" Command="telerik:RadGridViewCommands.Delete" CommandParameter="{Binding}">Delete</telerik:RadButton>
                    </DataTemplate>
                </telerik:GridViewDataColumn.CellTemplate>
            </telerik:GridViewDataColumn>
            <telerik:GridViewDataColumn Header="Record" DataMemberBinding="{Binding League, Mode=TwoWay}" Width="*" IsFilterable="False" />
            <telerik:GridViewDataColumn Header="Active" DataMemberBinding="{Binding Active, Mode=TwoWay}" Width="150">
                <telerik:GridViewDataColumn.CellTemplate>
                    <DataTemplate>
                        <CheckBox IsChecked="{Binding Active}" IsEnabled="True" />
                    </DataTemplate>
                </telerik:GridViewDataColumn.CellTemplate>
            </telerik:GridViewDataColumn>
        </telerik:RadGridView.Columns>
    </telerik:RadGridView>
</Grid>


Here's my code-behind:

private void recordsDomainDataSource_LoadedData(object sender, System.Windows.Controls.LoadedDataEventArgs e)
{
    if (e.HasError)
    {
        System.Windows.MessageBox.Show(e.Error.ToString(), "Load Error", System.Windows.MessageBoxButton.OK);
        e.MarkErrorAsHandled();
    }
}
private void rgvRecords_RowEditEnded(object sender, Telerik.Windows.Controls.GridViewRowEditEndedEventArgs e)
{
    recordsDomainDataSource.DomainContext.SubmitChanges();
}
private void rgvRecords_Deleted(object sender, Telerik.Windows.Controls.GridViewDeletedEventArgs e)
{
    recordsDomainDataSource.DomainContext.SubmitChanges();
}


Here's my problem...The record has three members:

RecordID uniqueidentifier
Record nvarchar
IsActive bit

The RecordID has a default value of (newid()) in the SQL table. However, when I try to click add, a null GUID (0000-....) is assigned to the new record.  This, then, prohibits me from adding another record (not to mention, I don't want the record to have a null GUID).

I don't really know how to ask this, but is there a way to pull the new default GUID from the new inserted item?  Previously, before RIA services I was using an Insert statement with an OUTPUT clause.  Otherwise, if I create the GUID in code, where do I assign it to the new record prior to insertion?

I've tried changing the Services.metadata.cs attribute for RecordID to [Key], also to [ReadOnly(true)], and even removing the setter from the member. Neither of these worked as a null GUID was still inserted into the database.

Thanks.
Joshua
0
Joshua
Top achievements
Rank 1
answered on 24 Aug 2010, 08:50 PM
nevermind, figured it out. thanks for all of your help.

- Joshua
Tags
GridView
Asked by
Joshua
Top achievements
Rank 1
Answers by
Joshua
Top achievements
Rank 1
Yavor Georgiev
Telerik team
Share this question
or