Show message after a successful record saving - c#

I am new to XAF Blazor so I trying to display a message to end users after a successful record saving, so I wrote the following code:
public partial class MessageSavedSuccessfullyViewController : ViewController
{
public MessageSavedSuccessfullyViewController()
{
InitializeComponent();
}
protected override void OnActivated()
{
base.OnActivated();
View.ObjectSpace.Committing += ObjectSpace_Committing;
}
protected override void OnViewControlsCreated()
{
base.OnViewControlsCreated();
}
protected override void OnDeactivated()
{
View.ObjectSpace.Committing -= ObjectSpace_Committing;
base.OnDeactivated();
}
private void ObjectSpace_Committing(object sender, CancelEventArgs e)
{
if (View.ObjectSpace.IsCommitting)
{
MessageOptions options = new();
options.Duration = 2000;
options.Message = string.Format("Record Saved Successfully");
options.Type = InformationType.Success;
options.Web.Position = InformationPosition.Right;
options.Win.Caption = "Success";
options.Win.Type = WinMessageType.Toast;
Application.ShowViewStrategy.ShowMessage(options);
}
}
}
but when I run the code, nothing happens.
Is there something I am missing?
This code should be used across my entire application, not just in a specific view.

public partial class MessageSavedSuccessfullyViewController : ViewController<DetailView>
{
private string message;
public MessageSavedSuccessfullyViewController()
{
InitializeComponent();
}
protected override void OnActivated()
{
base.OnActivated();
View.ObjectSpace.ObjectChanged += ObjectSpace_ObjectChanged;
View.ObjectSpace.Committed += ObjectSpace_Committed;
}
protected override void OnViewControlsCreated()
{
base.OnViewControlsCreated();
}
protected override void OnDeactivated()
{
View.ObjectSpace.ObjectChanged -= ObjectSpace_ObjectChanged;
View.ObjectSpace.Committed -= ObjectSpace_Committed;
base.OnDeactivated();
}
void ObjectSpace_Committed(object sender, EventArgs e)
{
MessageOptions options = new();
options.Duration = 2000;
options.Message = message;
options.Type = InformationType.Success;
options.Web.Position = InformationPosition.Right;
options.Win.Caption = "Success";
options.Win.Type = WinMessageType.Toast;
Application.ShowViewStrategy.ShowMessage(options);
message = string.Empty;
}
void ObjectSpace_ObjectChanged(object sender, ObjectChangedEventArgs e)
{
if (ObjectSpace.IsNewObject(e.Object))
{
message=string.Format("Record Saved Successfully");
}
else if (ObjectSpace.IsDeleting)
{
message = string.Format("Record Deleted Successfully");
}
else if (ObjectSpace.IsModified && e.OldValue != e.NewValue)
{
message = string.Format("Record Updated Successfully");
}
}
}

Related

C# UserControl Button click adds items to listbox from form1

I'm working on a C# app,that searches for song names on youtube (using youtube api) and displaying the data, I have a custom SongItem (UserControl) and I add them to a FlowLayoutControl. I added a "Favourite" button to the UserControl, and I need that to add itself to another FlowLayoutControl that's the Favourited song list, but I can't get that working, I can't have multiple base classes in the UserControl,and adding a public method to Form1, doesn't solve my issue, (it's not adding anything,tried it with listbox,but nothing).
I'm really stuck here,if someone can at least suggest something I would rly appreciate it.
Here is my SongItem
[Serializable]
public partial class SongItem : UserControl,Form
{
private String songName = "Song Name";
private String artistName = "Artist Name";
private Image thumbNail;
private String length;
private int maxLengthSongName = 25;
private int maxLengthArtistName = 25;
private Color colorHoverOn = Color.FromArgb(53,53,53);
private Color colorNormal = Color.FromArgb(53,53,53);
private SongData songData;
public SongItem()
{
InitializeComponent();
this.MouseClick += Control_MouseClick;
MouseEvents(this);
}
private void SongItem_Load(object sender, EventArgs e)
{
try
{
LoadData();
}
catch { }
LoadDataToUI();
}
#region GettersAndSetters
public int MaxLengthSongName
{
get { return maxLengthSongName; }
set { maxLengthSongName = value; }
}
public int MaxLengthArtistName
{
get { return maxLengthArtistName; }
set { maxLengthArtistName = value; }
}
public Color ColorHoverOn
{
get { return colorHoverOn; }
set { colorHoverOn = value; }
}
public Color ColorNormal
{
get { return colorNormal; }
set { colorNormal = value; }
}
public SongData SongData {
get{return songData; }
set { songData = value; }
}
#endregion
public void LoadData()
{
songName = songData.SongName;
artistName = songData.ArtistName;
thumbNail = songData.ThumbNail;
length = songData.Length;
}
void MouseEvents(Control container)
{
foreach (Control c in container.Controls)
{
c.MouseEnter += (s, e) => SongItem_MouseEnter(e);
c.MouseLeave += (s, e) => SongItem_MouseLeave(e);
c.MouseClick += Control_MouseClick;
MouseEvents(c);
};
}
private void SongNameLbl_MouseHover(object sender, EventArgs e)
{
if (songName.Length > maxLengthSongName) {
toolTip1.SetToolTip(songNameLbl, songName);
}
}
private void ArtistNameLbl_MouseHover(object sender, EventArgs e)
{
if (artistName.Length > maxLengthArtistName) {
toolTip1.SetToolTip(artistNameLbl, artistName);
}
}
private void SongNameLbl_Click(object sender, EventArgs e)
{
Clipboard.SetText(artistName + " " +songName);
}
#endregion
#region CurrentlySelected
public event EventHandler<EventArgs> WasClicked;
private void Control_MouseClick(object sender, MouseEventArgs e)
{
var wasClicked = WasClicked;
if (wasClicked != null)
{
WasClicked(this, EventArgs.Empty);
}
IsSelected = true;
}
private bool _isSelected;
public bool IsSelected
{
get { return _isSelected; }
set
{
_isSelected = value;
this.BorderStyle = IsSelected ? BorderStyle.FixedSingle : BorderStyle.None;
}
}
#endregion
private void Fovourite_Click(object sender, EventArgs e)
{
Main newMain = new Main();
// newMain.AddSongToFavorite();
newMain.listBox1.Items.Add("Test");
}
}
}
Here is the the Form1 code
public void AddSongToFavorite() {
listBox1.Items.Add("Test");
//songList2.AddSong("Dire Straits - Sultans Of Swing");
MessageBox.Show("Hello", "Test");
// flowLayoutPanel1.Controls.Add(song);
}
Message shows up,but nothing else
I add the SongItem from another class
public partial class SongList : FlowLayoutPanel
{
public SongList()
{
InitializeComponent();
SongList_Load();
}
private void SongList_Load()
{
this.AutoScroll = true;
this.FlowDirection = FlowDirection.TopDown;
this.AutoSize = false;
this.WrapContents = false;
}
public async void AddSong(String songName) {
SongData song = await YoutubeSearch.GetSongInfo(songName);
// SongData song = XmlSerialization.ReadFromXmlFile<SongData>(Application.StartupPath + #"\test.txt");
SongItem songItem = new SongItem { SongData = song };
songItem.WasClicked += UsersGrid_WasClicked;
this.Controls.Add(songItem);
}
I fixed the problem by creating an EventHandler
In the main I created this public void
public void FavoriteWasClicked(object sender, EventArgs e) {
if (sender is SongItem)
{
songList2.AddSong(((SongItem)sender).SongData);
}
}
and on Form1 load I added (songList1 is the FlowLayoutPanel already added in the Form1 designer)
songList1.List_FavoriteWasClicked += FavoriteWasClicked;
I added this line to the FlowLayoutPanel class I created
public event EventHandler<EventArgs> List_FavoriteWasClicked;
and when creating new Controls(SongItems inside it)(Still part of FlowLayoutPanel)
public void AddSong(SongData song)
{
SongItem songItem = new SongItem { SongData = song };
songItem.FavoriteWasClicked += List_FavoriteWasClicked; ()
this.Controls.Add(songItem);
}
And now on the SongItem I created the custom event
public event EventHandler<EventArgs> FavoriteWasClicked;
and on the button I wanted to be the press to add to favorite list I added the following
FavoriteWasClicked(this, EventArgs.Empty);
Now when I press the button to add one Song to the liked/favorited list it's actually adding it.

Can't change TextBox.Text from another form

I have the following C# code in my winform application:
FormPrincipale
private void butFornitore_Click(object sender, EventArgs e)
{
try
{
FormFornitore Dialog = new FormFornitore();
Dialog.ShowDialog();
}
catch(Exception excDial)
{
MessageBox.Show("DIALOG: " + excDial.Message);
}
}
public void getFornitore(string Codice, string Descrizione)
{
this.txtFornitore.Text = Descrizione;
Fornitore = Codice;
}
FormFornitore
private void gridFornitori_DoubleClick(object sender, EventArgs e)
{
try
{
var Codice = gridView2.GetFocusedDataRow()["codconto"].ToString();
var RagSoc = gridView2.GetFocusedDataRow()["dscconto1"].ToString();
FormPrincipale Form = new FormPrincipale();
Form.getFornitore(Codice, RagSoc);
this.Close();
}
catch(Exception excGrid)
{
MessageBox.Show("GRID: " + excGrid.Message);
}
}
The code works (i used breakpoints to check if code was executed) but the Text property of the TextBox doesn't change. I put Modifiers TextBox property on Public, so this is ok too. I'm using Dev Express Grid Control, but i don't think this is the problem. Thank's for help.
To pass the instance of your parent form, you could do something like this:
class FormFornitore: Form
{
protected FormPrincipale parent;
FormFornitore(FormPrincipale parent)
{
this.parent = parent;
}
private void gridFornitori_DoubleClick(object sender, EventArgs e)
{
try
{
var Codice = gridView2.GetFocusedDataRow()["codconto"].ToString();
var RagSoc = gridView2.GetFocusedDataRow()["dscconto1"].ToString();
/// REMOVE THIS FormPrincipale Form = new FormPrincipale();
parent.getFornitore(Codice, RagSoc);
this.Close();
}
catch(Exception excGrid)
{
MessageBox.Show("GRID: " + excGrid.Message);
}
}
}
Then in your "FormPricipale" use it like this
private void butFornitore_Click(object sender, EventArgs e)
{
try
{
FormFornitore Dialog = new FormFornitore(this); // Notice the argument
Dialog.ShowDialog();
}
catch(Exception excDial)
{
MessageBox.Show("DIALOG: " + excDial.Message);
}
}
public void getFornitore(string Codice, string Descrizione)
{
this.txtFornitore.Text = Descrizione;
Fornitore = Codice;
}

c# - Cannot convert from void to list

So, I got kind of stuck over my head while I tried to program something new.
I'm trying to add objectBeer_pluche or objectBeer_Elektro to my OBJberenlijst on the Beren Main form from the details Form, so I can add both instances of 2 classes to the same list.
I'm not even sure this is possible by the way. So, I would like feedback if what I am trying to do is possible to start with. I already figured VOID is not right but I am really clueless here.
This is my main beren.cs form with an OBJberenlist, that's where I try to add objectBeer_pluche or objectBeer_Elektro into it:
public partial class Beren : Form
{
public interface Berenlijst { }
public List<Berenlijst> OBJberenLijst = new List<Berenlijst>();
public Beren()
{
InitializeComponent();
}
private void Beren_Load(object sender, EventArgs e)
{
}
private void BTNToevoegen_Click(object sender, EventArgs e)
{
this.Hide();
Details Details = new Details();
if (Details.ShowDialog(this) == DialogResult.OK)
{
OBJberenLijst.Add(Details.getdetails());
}
Details.Close();
Details.Dispose();
}
public void LijstLaden()
{
foreach(Beer berenobject in OBJberenLijst)
{
LST_beren.Items.Add(berenobject.Naam);
}
}
}
}
from this form called details.cs
public partial class Details : Form
{
public Details()
{
InitializeComponent();
BTN_toevoegen.DialogResult = DialogResult.OK;
BTN_cancel.DialogResult = DialogResult.Cancel;
}
private void Details_Load(object sender, EventArgs e)
{
RDB_pluche.Checked = true;
BTN_ok.Enabled = false;
}
private void RDB_pluche_CheckedChanged(object sender, EventArgs e)
{
PANEL_pluche.Visible = true;
PANEL_elektro.Visible = false;
}
private void RDB_elektro_CheckedChanged(object sender, EventArgs e)
{
PANEL_pluche.Visible = false;
PANEL_elektro.Visible = true;
}
private void BTN_toevoegen_Click(object sender, EventArgs e)
{
open_foto.Filter = "jpg (*.jpg)|*.jpg|bmp(*.bmp)|*.bmp|png(*.png)|*.png";
if (open_foto.ShowDialog() == System.Windows.Forms.DialogResult.OK && open_foto.FileName.Length > 0)
{
TXT_adres.Text = open_foto.FileName;
PIC_beer.Image = Image.FromFile(open_foto.FileName);
}
}
private void BTN_ok_Click(object sender, EventArgs e)
{
}
public void getdetails()
{
if (RDB_pluche.Enabled == true)
{
Pluche_Beer objectBeer_pluche = new Pluche_Beer(TXTNaam_pluche.Text, open_foto.FileName, "(Wasprogramma: " + TXT_wasprogramma.ToString() + " Graden Celsius");
}
else
{
Elektronische_Beer objectBeer_Elektro = new Elektronische_Beer(TXTNaam_elekro.Text, open_foto.FileName, "aantal Batterijen: " + CMBOBatterijen.ToString());
}
}
private void Details_MouseMove(object sender, MouseEventArgs e)
{
foreach (Control c in this.Controls)
{
if (c is TextBox)
{
TextBox textBox = c as TextBox;
if (textBox.Text != string.Empty)
{
BTN_ok.Enabled = true;
}
}
}
}
}
}
The problem is between this line...
OBJberenLijst.Add(Details.getdetails());
...and this line.
public void getdetails()
List.Add() requires an object to add, but getdetails() returns void. You probably want to change getdetails() to something like the following:
public Berenlijst getdetails()
{
if (RDB_pluche.Enabled == true)
{
return new Pluche_Beer(TXTNaam_pluche.Text, open_foto.FileName, "(Wasprogramma: " + TXT_wasprogramma.ToString() + " Graden Celsius");
}
return new Elektronische_Beer(TXTNaam_elekro.Text, open_foto.FileName, "aantal Batterijen: " + CMBOBatterijen.ToString());
}
Hopefully Pluche_Beer and Elektronisch_Beer inherent from Berenlijst. Otherwise you'll have to revise your logic in a broader way.

How to check Button clicked in general methode?

I have tried with below
public partial class PaymentSearch : System.Web.UI.Page
{
private bool button1WasClicked = false;
protected void linkToday_Click(object sender, EventArgs e)
{
button1WasClicked = true;
}
protected void ddlRecordPayment_SelectedIndexChanged(object sender, EventArgs e)
{
gridAllPaymentBind(1);
}
public void gridAllPaymentBind(int pageIndex)
{
if (button1WasClicked == true)
{
result = 3;
command.Parameters.AddWithValue("#result", result);
}
}
but in 'gridAllPaymentBind' methode ' button1WasClicked' getting false value where I alredy clicked link button before dropdown list change event fire.
try like below...
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack == true)
{
Session["button1WasClicked "] = false;
}
}
protected void linkToday_Click(object sender, EventArgs e)
{
Session["button1WasClicked "] = true;
}
protected void ddlRecordPayment_SelectedIndexChanged(object sender, EventArgs e)
{
gridAllPaymentBind(1);
}
public void gridAllPaymentBind(int pageIndex)
{
bool button1WasClicked = (bool)Session["button1WasClicked "];
if (button1WasClicked == true)
{
result = 3;
command.Parameters.AddWithValue("#result", result);
}
}
hope this will help you..good luck.
ASP.NET by nature is stateless so the variable value will not persist between postbacks. So to make it persistent you can use either a Session or ViewState.
public partial class PaymentSearch : System.Web.UI.Page
{
private bool button1WasClicked
{
get { return (bool)Session["button1WasClicked"]; }
set { Session["button1WasClicked"] = value; }
}
protected void linkToday_Click(object sender, EventArgs e)
{
button1WasClicked = true;
}
protected void ddlRecordPayment_SelectedIndexChanged(object sender, EventArgs e)
{
gridAllPaymentBind(1);
}
public void gridAllPaymentBind(int pageIndex)
{
if (button1WasClicked == true)
{
result = 3;
command.Parameters.AddWithValue("#result", result);
}
}
}

Fill DataGridView on FbRemoteEvent

I have one MainForm (with dataGridView) and DataModule class with my own LoadDataTable method which execute FbCommand select sql and fill datatable in dataset and FbRemoteEvent catch method. When I run my app, in MainForm_OnLoad I call LoadDataTable method and my dataGridView show data successfully. But when my app catch FbRemoteEvent from server and call LoadDataTable method, exception occurred in dataGridView. Why?
MainForm:
public partial class MainForm : Form
{
private readonly DataModule _dataModule = DataModule.GetInstance();
public MainForm()
{
InitializeComponent();
}
private void MainForm_Load(object sender, EventArgs e)
{
dataGridView1.AutoGenerateColumns = false;
dataGridView1.DataSource = _dataModule.AppDataSet;
dataGridView1.DataMember = "MESSAGEQUEUE";
_dataModule.LoadMessageQueueDataTable();
}
}
DataModule:
private void FirebirdRemoteEventOnRemoteEventCounts(object sender, FbRemoteEventEventArgs fbRemoteEventEventArgs)
{
switch (fbRemoteEventEventArgs.Name.Trim().ToUpper())
{
case "QUEUE_NEW_MESSAGE":
if (fbRemoteEventEventArgs.Counts > 0)
{
LoadMessageQueueDataTable();
}
break;
}
}
public void LoadMessageQueueDataTable()
{
if (ConnectToFirebird())
{
using (var firebirdTransaction = FirebirdConnection.BeginTransaction())
{
using (var firebirdCommand = new FbCommand
{
Connection = firebirdTransaction.Connection,
Transaction = firebirdTransaction,
CommandType = CommandType.Text,
CommandText = "select MESSAGEQUEUEID, CREATEDATETIME, SENDER, RECIPIENT, TEXT from MESSAGEQUEUE"
})
{
AppDataSet.Tables["MESSAGEQUEUE"].Clear();
try
{
AppDataSet.Tables["MESSAGEQUEUE"].Load(firebirdCommand.ExecuteReader());
firebirdCommand.Transaction.Commit();
}
catch (FbException firebirdException)
{
firebirdCommand.Transaction.Rollback();
}
}
}
}
}
Error:
In DataModule class add and change FbRemoteEvent handler:
public delegate void DelegateMessageQueueTableUpdate();
public event DelegateMessageQueueTableUpdate MessageQueueTableUpdate;
private void FirebirdRemoteEventOnRemoteEventCounts(object sender, FbRemoteEventEventArgs fbRemoteEventEventArgs)
{
switch (fbRemoteEventEventArgs.Name.Trim().ToUpper())
{
case "QUEUE_NEW_MESSAGE":
if (fbRemoteEventEventArgs.Counts > 0)
{
if (MessageQueueTableUpdate != null)
{
MessageQueueTableUpdate();
}
}
break;
}
}
In MainForm:
public partial class MainForm : Form
{
private readonly DataModule _dataModule = DataModule.GetInstance();
private delegate void RefreshMessageQueueTable();
public MainForm()
{
InitializeComponent();
_dataModule.MessageQueueTableUpdate += () =>
{
if (dataGridView1.InvokeRequired)
{
dataGridView1.Invoke(new RefreshMessageQueueTable(_dataModule.LoadMessageQueueDataTable));
}
else
{
_dataModule.LoadMessageQueueDataTable();
}
};
}
private void MainForm_Load(object sender, EventArgs e)
{
dataGridView1.DataSource = _dataModule.AppDataSet;
dataGridView1.DataMember = "MESSAGEQUEUE";
_dataModule.LoadMessageQueueDataTable();
}
}

Categories