5【MySQL】MAUIでデータベースへ新規登録&更新
CollectionViewにSelectionChangedを追加する
<CollectionView x:Name="BalanceCollection" ItemsSource="{Binding balances.Value}" SelectionMode="Single" SelectionChanged="BalanceCollection_SelectionChanged">
呼び出すメソッド内で、Entry に選択中のデータを反映させます。
void BalanceCollection_SelectionChanged(System.Object sender, Microsoft.Maui.Controls.SelectionChangedEventArgs e)
{
updateParamater = true;
//DateTime? previousPD = (e.PreviousSelection.FirstOrDefault() as Balance)?.paydate;
DateTime CurrentPD = (e.CurrentSelection.FirstOrDefault() as Balance).paydate;
DateTime CurrentID = (e.CurrentSelection.FirstOrDefault() as Balance).invoicedate;
int CurrentP = (e.CurrentSelection.FirstOrDefault() as Balance).price;
string CurrentBN = (e.CurrentSelection.FirstOrDefault() as Balance).bname;
string? CurrentBC = (e.CurrentSelection.FirstOrDefault() as Balance)?.bcompany;
string? CurrentBM = (e.CurrentSelection.FirstOrDefault() as Balance)?.bmemo;
bool CurrentIC = (e.CurrentSelection.FirstOrDefault() as Balance).iscash;
int Currentid = (e.CurrentSelection.FirstOrDefault() as Balance).idbalance;
currentid = Currentid;
E_PAY.Date = CurrentPD;
E_INV.Date = CurrentID;
E_PRI.Text = CurrentP.ToString();
E_BNA.Text = CurrentBN;
E_BCO.Text = CurrentBC;
E_BME.Text = CurrentBM;
}
public void UpdateBalanceData
(
#nullable enable
int idb, DateTime payD, DateTime invD, int pr, string bna, string? bco, string? bme, bool cash
)
{
var balance = new Balance
{
idbalance = idb,
paydate = payD,
invoicedate = invD,
price = pr,
bname = bna,
bcompany = bco,
bmemo = bme,
iscash = cash
};
var service = new DBService();
service.UpdateBalanceData(balance);
Update();
}
public void AddBalanceClicked(System.Object sender, System.EventArgs e)
{
if (updateParamater == true)
{//一つのButtonで更新と新規登録を判別する
balances.Value = new();
UpdateBalanceData(
idb: currentid,
payD: E_PAY.Date,
invD: E_INV.Date,
pr: priceint = Int32.Parse(E_PRI.Text),
bna: E_BNA.Text,
bco: E_BCO.Text,
bme: E_BME.Text,
cash: currentIC
);
}
else
{
balances.Value = new();
AddBalanceData(
payD: E_PAY.Date, //= DateTime.ParseExact($"{E_PAY.Date}", "yyyy-MM-dd", null),
invD: E_INV.Date, //= DateTime.ParseExact($"{E_INV.Date}", "yyyy-MM-dd", null),
pr: priceint = Int32.Parse(E_PRI.Text),
bna: E_BNA.Text,
bco: E_BCO.Text,
bme: E_BME.Text,
cash: true
);
}
}
初心者なので余計なコードもあるかもしれません。
上記までがViewModel.csのコード。
その中の下記のコードが、DBSevice.csという直接データベースに接続するためのクラスのメソッドを呼び出すものです。
service.UpdateBalanceData(balance);
※DBService.csの中身は過去記事に少し掲載しています。
matsrikagraphic.hatenablog.com
これでとりあえず、データベースをリアルタイムで操作できるようになりました。