How to use picturebox in MVP C#

KHALID ALI 1 Reputation point
2020-12-12T06:56:58.35+00:00

i have forum with picturebox and some texts so i want to insert photo to database how can i do that .

i want to save image to the table by stored procedure in sql using MVP c# so i start with stored procedure :

Create procedure [dbo].[Save_Customer]

@CustomerID int,
@CustomerName nvarchar (150),
@CustomerEmail nvarchar (50),
@CustomerPhone int,
@CustomerStatus bit,
@CustomerPhoto image

As
BEGIN

INSERT INTO dbo.CustomersTbl (CustomerID, CustomerName, CustomerEmail, CustomerPhone, CustomerStatus, CustomerPhoto)
VALUES (@CustomerID, @CustomerName, @CustomerEmail, @CustomerPhone, @CustomerStatus, @CustomerPhoto);

Return -2;

END

now i start now project and form added with :

4 Textboxs

1 checkbox

and 1 PictuerBox

and 1 button ( Save )

now i have create class Called DBhelper which contain connection and insert method :

DBHelper class :

namespace TestMVP.Logic.Services
{
    static public class DBHelper
    {
        public static SqlCommand command;
        private static SqlConnection GetConnectionString()
        {
            SqlConnection sqlconnection = new SqlConnection(ConfigurationManager.ConnectionStrings["connSQLServer"].ConnectionString);

            return new SqlConnection(ConfigurationManager.ConnectionStrings["connSQLServer"].ConnectionString);
        }

        //Method To Insert , Update And Delete From Database
        public static bool ExcuteData(string SpName, Action method)
        {
            using (SqlConnection connection = GetConnectionString())
            {
                try
                {
                    command = new SqlCommand(SpName, connection);
                    command.CommandType = CommandType.StoredProcedure;
                    method.Invoke();
                    connection.Open();
                    command.ExecuteNonQuery();
                    connection.Close();
                    return true;
                }
                catch (Exception ex)
                {
                    connection.Close();
                    Console.WriteLine(ex.Message);
                    return false;
                }
                finally
                {
                    connection.Close();
                }
            }
        }
}

Now i added another class called

Models:

namespace TestMVP.Models
{
    class OpsModel
    {
        public int CustomerID { get; set; }
        public string CustomerName { get; set; }
        public string CustomerEmail { get; set; }
        public string CustomerPhone { get; set; }
        public bool CustomerStatus { get; set; }
        public byte CustomerPhoto { get; set; }

    }
}

and i add another class called :

OpsService :

namespace TestMVP.Logic.Services
{
    static class OpsService
    {
        //This Method For Insert Paramerters For Customer To Database
        private static void CumstomerParamerterInsert(int CustomerID, string CustomerName, string CustomerEmail, string CustomerPhone, bool CustomerStatus, byte CustomerPhoto, SqlCommand command)
        {
            command.Parameters.Add("@CustomerID", SqlDbType.Int).Value = CustomerID;
            command.Parameters.Add("@CustomerName", SqlDbType.NVarChar, 150).Value = CustomerName;
            command.Parameters.Add("@CustomerEmail", SqlDbType.NVarChar, 50).Value = CustomerEmail;
            command.Parameters.Add("@CustomerPhone", SqlDbType.NVarChar, 10).Value = CustomerPhone;
            command.Parameters.Add("@CustomerStatus", SqlDbType.Bit).Value = CustomerStatus;
            command.Parameters.Add("@CustomerPhoto", SqlDbType.Image).Value = CustomerPhoto;
        }

        //This Method For Insert Customer To Database
        static public bool InsertCustomer(int CustomerID, string CustomerName, string CustomerEmail, string CustomerPhone, bool CustomerStatus, byte CustomerPhoto)
        {
            return DBHelper.ExcuteData("Save_Customer", () => CumstomerParamerterInsert(CustomerID, CustomerName, CustomerEmail, CustomerPhone, CustomerStatus, CustomerPhoto, DBHelper.command));
        }
}

and i add interface class :

namespace TestMVP.Views.Inerfaces
{
    public interface IOps
    {
        int CustomerID { get; set; }
        string CustomerName { get; set; }
        string CustomerEmail { get; set; }
        string CustomerPhone { get; set; }
        bool CustomerStatus { get; set; }
        object DataGridView { get; set; }
        DataGridView DataGridViewRows { get; set; }
        object simpleButton2 { get; set; }
        object simpleButton3 { get; set; }
        object simpleButton4 { get; set; }
        object Cbx { get; set; }
        string CustomerDisplayMember { get; set; }
        string CustomerValueMember { get; set; }
        byte CustomerPhoto { get; set; }
    }
}

and the presenter class contain :

namespace TestMVP.Logic.Presenter
{
    class OpsPresenter
    {
        IOps iops;
        OpsModel opsModel = new OpsModel();

        public OpsPresenter(IOps view)
        {
            iops = view;
        }

        // Connect Between Model And Interface
        private void ConnectBetweenModelAndInterface()
        { 

            opsModel.CustomerID = iops.CustomerID;
            opsModel.CustomerName = iops.CustomerName;
            opsModel.CustomerEmail = iops.CustomerEmail;
            opsModel.CustomerPhone = iops.CustomerPhone;
            opsModel.CustomerStatus = iops.CustomerStatus;
            opsModel.CustomerPhoto =iops.CustomerPhoto;
        }

        // Insert Customer To Database
        public void CusInsert()
        {
            if (iops.CustomerName == "")
            {
                MessageBox.Show("Please Enter Customer Name");
                return;
            }
            if (iops.CustomerEmail == "")
            {
                MessageBox.Show("Please Enter Customer Email");
                return;
            }
            if (iops.CustomerPhone == "")
            {
                MessageBox.Show("Please Enter Customer Phone");
                return;
            }
            else
            {
                ConnectBetweenModelAndInterface();
                OpsService.InsertCustomer(opsModel.CustomerID, opsModel.CustomerName, opsModel.CustomerEmail, opsModel.CustomerPhone, opsModel.CustomerStatus, opsModel.CustomerPhoto);
                GetAllCus();
                AutoNumber();
                MessageBox.Show("Customer Added ...");
            }
        }
}

and last i call the presenter in save button:

namespace TestMVP.Views.Forms
{
    public partial class FrmOps : DevExpress.XtraEditors.XtraForm, IOps
    {
        OpsPresenter opsPresenter;
        CLS_Main Caller = new CLS_Main();
        public FrmOps()
        {
            InitializeComponent();
            opsPresenter = new OpsPresenter(this);
        }

        public int CustomerID { get => Convert.ToInt32(textBox1.Text); set => textBox1.Text = value.ToString(); }
        public string CustomerName { get => textBox2.Text; set => textBox2.Text = value.ToString(); }
        public string CustomerEmail { get => textBox3.Text; set => textBox3.Text = value.ToString(); }
        public string CustomerPhone { get => textBox4.Text; set => textBox4.Text = value.ToString(); }
        public bool CustomerStatus { get => checkBox1.Checked; set => checkBox1.Checked = value; }
        public object DataGridView { get => dataGridView1.DataSource; set => dataGridView1.DataSource = value; }
        object IOps.simpleButton2 { get => simpleButton2.Enabled; set => simpleButton2.Enabled = Convert.ToBoolean(value); }
        object IOps.simpleButton3 { get => simpleButton3.Enabled; set => simpleButton3.Enabled = Convert.ToBoolean(value); }
        object IOps.simpleButton4 { get => simpleButton4.Enabled; set => simpleButton4.Enabled = Convert.ToBoolean(value); }
        public DataGridView DataGridViewRows { get => dataGridView1; set => dataGridView1.DataSource = value; }
        public object Cbx { get => comboBox1.DataSource; set => comboBox1.DataSource = value; }
        public string CustomerDisplayMember { get => comboBox1.DisplayMember; set => comboBox1.DisplayMember = value; }
        public string CustomerValueMember { get => comboBox1.ValueMember; set => comboBox1.ValueMember = value; }
        public byte CustomerPhoto { get => Convert.ToByte(pictureBox1.Image); set => pictureBox1.Image = Resources.UserPic; }
        private void FrmOps_Load(object sender, EventArgs e)
        {
            opsPresenter.AutoNumber();
            opsPresenter.GetAllCus();
            opsPresenter.FillCbx();
        }

        private void simpleButton2_Click(object sender, EventArgs e)
        {
            opsPresenter.CusInsert();
        }
}

how to save image to the table and convert it to binary .

Thanks...

Windows Forms
Windows Forms
A set of .NET Framework managed libraries for developing graphical user interfaces.
1,903 questions
.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,921 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,011 questions
VB
VB
An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
2,737 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Alberto Poblacion 1,561 Reputation points
    2020-12-25T10:59:13.663+00:00

    First of all, don't use the IMAGE type to save the image in the database. This is considered obsolete, in any versions of SQL Server newer than 2000, you should be using the VARBINARY(MAX) data type. This is not critical, the Image type should still work, it's just that you may find it deprecated in newer versions.

    Then a second thing is that all of the places where you treat your picturebox image as "byte" need to be changed to "byte[]". In other words, you need an array of bytes. A single byte, which is what you are using, is not sufficient for saving a whole picture.

    Then the final piece that you are missing is this one:
    [...] CustomerPhoto { get => Convert.ToByte(pictureBox1.Image); [...]

    This cannot work. You are trying to convert the whole image into a single byte. As we said before, it has to be an array of bytes.

    Fortunately, the Image object already has a method called SaveAs which can save the whole image. It is a bit tricky to use because it cannot save directly to an array of bytes. Instead, it saves to a Stream. But you can pass a MemoryStream for the Stream, and then pick up the bytes from the MemoryStream.

    MemoryStream ms = new MemoryStream();  
    pictureBox1.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);  
    byte[] theBytes = ms.ToArray();  
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.