首页 > 数据库 >SqlHelper + winfrom + datagridview操作图片

SqlHelper + winfrom + datagridview操作图片

时间:2023-12-05 17:22:06浏览次数:38  
标签:index SqlHelper pms winfrom datagridview dataGridView1 new public string

datagridview中单元格显示图片,图片的增删改查

点击单元格选择图片

 1、Employer

public class Employer
{
    public int Id;
    public string Name;
    public string PhoneNum;
    public string Address;
    public string Photo;
}

2、ObjectConvertUtil处理工具类,转换图片与字节

public class ObjectConvertUtil
{
    public static Image StringConvertToImage(string str)
    {
        byte[] byts = Convert.FromBase64String(str);
        MemoryStream ms = new MemoryStream(byts);
        Image img = System.Drawing.Image.FromStream(ms);
        return img;
    }

    public static string BitmapConvertToBase64(System.Drawing.Image bitmap)
    {
        MemoryStream ms1 = new MemoryStream();
        bitmap.Save(ms1, System.Drawing.Imaging.ImageFormat.Jpeg);
        byte[] arr1 = new byte[ms1.Length];
        ms1.Position = 0;
        ms1.Read(arr1, 0, (int)ms1.Length);
        ms1.Close();
        return Convert.ToBase64String(arr1);
    }
}

3、SqlHelper

public class SQLHelper
{
    //连接字符串
    private static readonly string connStr = "Data Source=DESKTOP-NJ2V6IC;Initial Catalog=Study;Integrated Security=True";

    //1.执行增、删、改的方法:ExecuteNonQuery
    public static int ExecuteNonQuery(string sql, params SqlParameter[] pms)
    {
        using (SqlConnection con = new SqlConnection(connStr))
        {
            using (SqlCommand cmd = new SqlCommand(sql, con))
            {
                if (pms != null)
                {
                    cmd.Parameters.AddRange(pms);
                }
                con.Open();
                return cmd.ExecuteNonQuery();
            }
        }
    }

    //2.封装一个执行返回单个对象的方法:ExecuteScalar()
    public static object ExecuteScalar(string sql, params SqlParameter[] pms)
    {
        using (SqlConnection con = new SqlConnection(connStr))
        {
            using (SqlCommand cmd = new SqlCommand(sql, con))
            {
                if (pms != null)
                {
                    cmd.Parameters.AddRange(pms);
                }
                con.Open();
                return cmd.ExecuteScalar();
            }
        }
    }

    //3.执行查询多行多列的数据的方法:ExecuteReader
    public static SqlDataReader ExecuteReader(string sql, params SqlParameter[] pms)
    {
        SqlConnection con = new SqlConnection(connStr);
        using (SqlCommand cmd = new SqlCommand(sql, con))
        {
            if (pms != null)
            {
                cmd.Parameters.AddRange(pms);
            }
            try
            {
                con.Open();
                return cmd.ExecuteReader(CommandBehavior.CloseConnection);
            }
            catch (Exception)
            {
                con.Close();
                con.Dispose();
                throw;
            }
        }
    }

    //4.执行返回DataTable的方法
    public static DataTable ExecuteDataTable(string sql, params SqlParameter[] pms)
    {
        DataTable dt = new DataTable();
        using (SqlDataAdapter adapter = new SqlDataAdapter(sql, connStr))
        {
            if (pms != null)
            {
                adapter.SelectCommand.Parameters.AddRange(pms);
            }
            adapter.Fill(dt);
        }
        return dt;
    }
}

4、页面

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    void LoadData()
    {
        try
        {
            dataGridView1.Rows.Clear();
            string sql = "select * from Employer";
            SqlDataReader sdr = SQLHelper.ExecuteReader(sql);
            if (sdr.HasRows)
            {
                while (sdr.Read())
                {
                    int index = dataGridView1.Rows.Add();
                    dataGridView1.Rows[index].Cells[0].Value = sdr[0].ToString();
                    dataGridView1.Rows[index].Cells[1].Value = sdr[1].ToString();
                    dataGridView1.Rows[index].Cells[2].Value = sdr[2].ToString();
                    dataGridView1.Rows[index].Cells[3].Value = sdr[3].ToString();
                    dataGridView1.Rows[index].Cells[4].Value = ObjectConvertUtil.StringConvertToImage(sdr[4].ToString());
                }
            }
            sdr.Close();
        }
        catch (Exception ex)
        {

        }
    }

    private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
    {
        if (this.dataGridView1.Columns[this.dataGridView1.CurrentCell.ColumnIndex].HeaderText == "头像")
        {
            OpenFileDialog open = new OpenFileDialog();
            if (open.ShowDialog() == DialogResult.OK)
            {
                string openfile = open.FileName;
                FileStream fs = new FileStream(openfile.Trim(), FileMode.Open);
                byte[] imageBytes = new byte[fs.Length];
                BinaryReader br = new BinaryReader(fs);
                imageBytes = br.ReadBytes(Convert.ToInt32(fs.Length));//图片转换成二进制流
                MemoryStream ms = new MemoryStream(imageBytes);
                Image img = System.Drawing.Image.FromStream(ms);

                this.dataGridView1.CurrentCell.Value = img;
            }
        }
    }

    /// <summary>
    /// 插入
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void button1_Click(object sender, EventArgs e)
    {
        try
        {
            int index = dataGridView1.CurrentRow.Index;
            if (index != -1)
            {
                Employer employer = new Employer();
                employer.Name = dataGridView1.Rows[index].Cells[1].Value.ToString();
                employer.PhoneNum = dataGridView1.Rows[index].Cells[2].Value.ToString();
                employer.Address = dataGridView1.Rows[index].Cells[3].Value.ToString();

                Image image = (Image)dataGridView1.Rows[index].Cells[4].Value;
                string phontoStr = ObjectConvertUtil.BitmapConvertToBase64(image);

                string sql = "insert into Employer(name,phoneNum,address,photo) values('" + employer.Name + "','" + employer.PhoneNum + "','" + employer.Address + "','" + phontoStr + "')";
                int i = SQLHelper.ExecuteNonQuery(sql);
                MessageBox.Show("添加成功");
                LoadData();
            }
        }
        catch (Exception ex)
        {

        }
    }

    /// <summary>
    /// 读取
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void button3_Click(object sender, EventArgs e)
    {
        LoadData();
    }
}

  

 

标签:index,SqlHelper,pms,winfrom,datagridview,dataGridView1,new,public,string
From: https://www.cnblogs.com/wokkkkkk/p/17877727.html

相关文章

  • Winfrom窗体初始化和窗体Load方法前后
    运行结果为【窗体初始化之前!】》【窗体初始化!】》【窗体Load!】 ......
  • SQLHelper帮助类库
    usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;usingMicrosoft.Data.SqlClient;usingSystem.Data;usingSystem.Configuration;namespaceYido.AdoNet.ToSQLServer{///<summary>......
  • c# winfrom pdf 预览
    在C#WinForms中预览PDF文件,你可以使用一些第三方库,比如iTextSharp或Ghostscript.NET。下面是一个使用iTextSharp的简单示例:首先,你需要安装iTextSharp库。你可以通过NuGet包管理器来安装。在VisualStudio中,打开Tools->NuGetPackageManager->ManageNuGetPackagesforSolut......
  • DataGridView循环刷新、导出为xlsx文件,加载保存json配置文件
    Winform中的DataGridView控件DataSource属性绑定到数据库,实现循环更新,并且可导出xsxl文件、暂停等功能。注:使用第三方库有EPPlus(操作Eecel)、Newtonsoft.net(Json序列化/反序列化)、Guna2(控件库)winform布局如下:创建LoadConFigJson方法:启动应用程序时,加载读取配置文件 ......
  • DataGridView绑定数据之后如何修改列值
    privatevoiddataGridView1_CellFormatting(objectsender,DataGridViewCellFormattingEventArgse){if(e==null||e.Value==null||!(senderisDataGridView))return;DataGridViewview=(DataGridView)send......
  • DataGridView的AutoGenerateColumns控制显示列
    在用C#的EF框架进行数据显示的时候出现了DataGridView显示未编辑列的问题,后来发现通过对DataGridView的 AutoGenerateColumns属性进行定义借可以解决AutoGenerateColumns属性默认未true,此时会显示所有,更改为false就可以了(此属性只能后台操控,代码加载main方法里)this.UsersDGV.......
  • C# WinFrom Application下的方法以及用法
    https://blog.csdn.net/weixin_44867439/article/details/132792736https://zhidao.baidu.com/question/177942555374414204.htmlApplication.Exit():用于退出应用程序。它会触发FormClosing事件,并允许窗体执行清理操作。一般来说,Application.Exit用于正常关闭应用程序。Applic......
  • datagridview消除自动生成的第一列
     方法:属性中 RowHeadersVisible设置为False效果: ......
  • winfrom窗体比例缩放
    用于控件大小随窗体大小等比例缩放的C#代码。该代码可以在窗体重载中使用,以确保窗体中的控件在窗体大小改变时能够按比例缩放。SetTag方法:该方法用于设置控件的Tag属性,以存储控件的宽度、高度、左边距、顶边距和字体大小等信息。SetControls方法:该方法用于遍历窗体中的控件,并根......
  • winfrom窗体比例缩放-
    用于控件大小随窗体大小等比例缩放的C#代码。该代码可以在窗体重载中使用,以确保窗体中的控件在窗体大小改变时能够按比例缩放。SetTag方法:该方法用于设置控件的Tag属性,以存储控件的宽度、高度、左边距、顶边距和字体大小等信息。SetControls方法:该方法用于遍历窗体中的控件,并根......