I want to insert image into the database, the Button that opens the Filepicker converts bitmapImage as I can make the image save to the database through the save button. Also read the database for image
in the part of showing the data a DataGrid (windows Community toolkit) is used
What I have tried:
Insert code for Data Base:
private async void BTInsert_Click(object sender, RoutedEventArgs e)
{
try
{
const string SqlString = "insert into PetTable(Pitcure,PetType,DuoDate,PetName,PetRace,PetColor,PetChip,PetGender,PetSterile) values (@picture,@pettype,@duoDate,@petName,@petRace,@petColor,@petChip,@petGender,@petSterile)";
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
if (conn.State == System.Data.ConnectionState.Open)
{
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = SqlString;
cmd.Parameters.Clear();
cmd.Parameters.Add("@picture", SqlDbType.Image).Value = Photo;
read for database
<pre>public static async Task<ObservableCollection<PetTable>> GetPets()
{
const string query = "SELECT PetType, DuoDate, PetName, PetRace, PetColor, PetChip, PetGender, PetSterile FROM PetTable";
var pets = new ObservableCollection<PetTable>();
try
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
await conn.OpenAsync();
using (SqlCommand cmd = new SqlCommand(query, conn))
{
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.HasRows)
{
while (reader.Read())
{
var pet = new PetTable
{
PetType = reader.GetString(0),
DuoDate = reader.GetDateTime(1),
PetName = reader.GetString(2),
PetRace = reader.GetString(3),
PetColor = reader.GetString(4),
PetChip = reader.GetString(5),
PetGender = reader.GetString(6),
PetSterile = reader.GetString(7)
};
pets.Add(pet);
}
}
}
}
}
return pets;
}
catch (Exception ex)
{
var Msg = new MessageDialog("Exeception:" + ex.Message);
Msg.Commands.Add(new UICommand("Close"));
}
return null;
}
open filePicker
private async void BTPhoto_Click(object sender, RoutedEventArgs e)
{
var OpenPicker = new FileOpenPicker();
OpenPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
OpenPicker.FileTypeFilter.Clear();
OpenPicker.FileTypeFilter.Add(".jpg");
OpenPicker.FileTypeFilter.Add(".jpeg");
OpenPicker.FileTypeFilter.Add(".png");
var file = await OpenPicker.PickSingleFileAsync();
if (file != null)
{
using (IRandomAccessStream fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read))
{
BitmapImage bitmapImage = new BitmapImage();
await bitmapImage.SetSourceAsync(fileStream);
Photo.Source = bitmapImage;
}
}
}