WindowsForms 调用API

WindowsForms 后台

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net.Http;
using Newtonsoft.Json;
using Aspose.Cells;
namespace WindowsDB2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
/// <summary>
/// 显示
/// </summary>
void Bind(string name="",int type=1)
{
Uri uri = new Uri("http://localhost:8231/");
HttpClient client = new HttpClient();
client.BaseAddress = uri;
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage mesa = client.GetAsync("actionApi/showApi/show?name=" + name + "&type=" + type).Result;
if (mesa.IsSuccessStatusCode)
{
var p = mesa.Content.ReadAsStringAsync().Result;
var js = JsonConvert.DeserializeObject<List<stuModel>>(p);
dataGridView1.AllowUserToAddRows = false;
dataGridView1.AutoGenerateColumns = false;
dataGridView1.DataSource = js;
}
}
/// <summary>
/// 下拉
/// </summary>
void xia()
{
Uri uri = new Uri("http://localhost:8231/");
HttpClient client = new HttpClient();
client.BaseAddress = uri;
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage mesa = client.GetAsync("actionApi/showApi/xia").Result;
if (mesa.IsSuccessStatusCode)
{
var p = mesa.Content.ReadAsStringAsync().Result;
var js = JsonConvert.DeserializeObject<List<stuType>>(p);
comboBox1.DisplayMember = "TypeName";
comboBox1.ValueMember = "Typeid";
comboBox1.DataSource = js;
}
}
/// <summary>
/// 加载 显示
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>

private void Form1_Load(object sender, EventArgs e)
{
xia();
Bind("", 1);
}
/// <summary>
/// 图片显示
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
DataGridView p = sender as DataGridView;
if (p.Columns[e.ColumnIndex].Name == "Tu")
{
e.Value = Image.FromFile(Application.StartupPath + "\\img\\" + e.Value);
}
}
/// <summary>
/// 添加
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button2_Click(object sender, EventArgs e)
{
Add d = new Add();
d.ShowDialog();
Bind("", 1);
}
/// <summary>
/// 导出
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button1_Click(object sender, EventArgs e)
{
Uri uri = new Uri("http://localhost:8231/");
HttpClient client = new HttpClient();
client.BaseAddress = uri;
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage mesa = client.GetAsync("actionApi/showApi/show").Result;
if (mesa.IsSuccessStatusCode)
{
var p = mesa.Content.ReadAsStringAsync().Result;
var js = JsonConvert.DeserializeObject<List<stuModel>>(p);
Workbook book = new Workbook();
Worksheet s = book.Worksheets[0];
Cells cell = s.Cells;
int i = 0;
cell[i, 0].PutValue("编号");
cell[i, 1].PutValue("名称");
cell[i, 2].PutValue("价格");
cell[i, 3].PutValue("图片");
cell[i, 4].PutValue("类型");
foreach (stuModel item in js)
{
i++;
cell[i, 0].PutValue(item.ID);
cell[i, 1].PutValue(item.Names);
cell[i, 2].PutValue(item.Price);
cell[i, 3].PutValue(item.Imgname);
cell[i, 4].PutValue(item.TypeName);
}
string newname = Guid.NewGuid().ToString() + ".xlsx";
book.Save(newname);
System.Diagnostics.Process.Start(Application.StartupPath + "\\" + newname);
}
}

private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
Bitmap p = new Bitmap(groupBox1.Width, groupBox1.Height);
groupBox1.DrawToBitmap(p, new Rectangle(0,0,p.Width, p.Height));
e.Graphics.DrawImage(p, 0, 0, p.Width, p.Height);
}
/// <summary>
/// 打印
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button4_Click(object sender, EventArgs e)
{
printPreviewDialog1.ShowDialog();
}
/// <summary>
/// 删除 修改
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
DataGridView p = sender as DataGridView;
DataGridViewRow row = p.Rows[e.RowIndex];
if (p.Columns[e.ColumnIndex].Name == "del")
{
var id = row.Cells[0].Value;
Uri uri = new Uri("http://localhost:8231/");
HttpClient client = new HttpClient();
client.BaseAddress = uri;
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage mesa = client.DeleteAsync("actionApi/showApi/shan?id=" + id).Result;
if (mesa.IsSuccessStatusCode)
{
var ppp = mesa.Content.ReadAsStringAsync().Result;
if (Convert.ToInt32(ppp) > 0)
{
MessageBox.Show("删除成功");
Bind("", 1);
}
}

}
if (p.Columns[e.ColumnIndex].Name == "update")
{
var id = row.Cells[0].Value;
xiu f = new xiu(Convert.ToInt32(id));
f.ShowDialog();
Bind("", 1);
}
}
/// <summary>
/// 全选
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button5_Click(object sender, EventArgs e)
{
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
dataGridView1.Rows[i].Cells[1].Value = true;
}
}

//批量删除

private void button6_Click(object sender, EventArgs e)
{
string id = string.Empty;
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
DataGridViewRow row = dataGridView1.Rows[i];
if (Convert.ToBoolean(row.Cells[1].Value))
{
id += row.Cells[0].Value + ",";
}
}
id = id.TrimEnd(',');
Uri uri = new Uri("http://localhost:8231/");
HttpClient client = new HttpClient();
client.BaseAddress = uri;
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage mesa = client.DeleteAsync("actionApi/showApi/shan?id=" + id).Result;
if (mesa.IsSuccessStatusCode)
{
var ppp = mesa.Content.ReadAsStringAsync().Result;
if (Convert.ToInt32(ppp) > 0)
{
MessageBox.Show("删除成功");
Bind("",1);
}
}
}

//查询

private void button3_Click(object sender, EventArgs e)
{
var name = textBox1.Text;
int type =Convert.ToInt32(comboBox1.SelectedValue);
Bind(name, type);
}
}
}

WindowsForms 添加

 

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace WindowsDB2
{
public partial class Add : Form
{
public Add()
{
InitializeComponent();
}
string tus = "";
void xia()
{
Uri uri = new Uri("http://localhost:8231/");
HttpClient client = new HttpClient();
client.BaseAddress = uri;
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage mesa = client.GetAsync("actionApi/showApi/xia").Result;
if (mesa.IsSuccessStatusCode)
{
var p = mesa.Content.ReadAsStringAsync().Result;
var js = JsonConvert.DeserializeObject<List<stuType>>(p);
comboBox1.DisplayMember = "TypeName";
comboBox1.ValueMember = "Typeid";
comboBox1.DataSource = js;
}
}
/// <summary>
/// 下拉的列表
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Add_Load(object sender, EventArgs e)
{
xia();
}
/// <summary>
/// 添加
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog p = new OpenFileDialog();
if (p.ShowDialog() == DialogResult.OK)
{
string flirename = p.FileName;
int page = flirename.LastIndexOf("\\");
string newname = Guid.NewGuid().ToString() + (flirename.Substring(page + 1));
using (FileStream ds = new FileStream(@".\img\" + newname, FileMode.CreateNew))
{
using (Stream str = p.OpenFile())
{
str.CopyTo(ds);
str.Flush();

stuModel m = new stuModel();
m.Names = textBox1.Text;
m.Price = Convert.ToInt32(textBox2.Text);
m.Typeid = Convert.ToInt32(comboBox1.SelectedValue);
m.Imgname = newname;
Uri uri = new Uri("http://localhost:8231/");
HttpClient client = new HttpClient();
client.BaseAddress = uri;
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
HttpContent cont = new StringContent(JsonConvert.SerializeObject(m));
cont.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");

HttpResponseMessage mesa = client.PostAsync("actionApi/showApi/add", cont).Result;
if (mesa.IsSuccessStatusCode)
{
var pp = mesa.Content.ReadAsStringAsync().Result;
if (Convert.ToInt32(pp) > 0)
{
MessageBox.Show("添加成功");
this.Close();
}
else
{
MessageBox.Show("添加失败");
}
}
pictureBox1.ImageLocation = (@".\img\" + newname).ToString();
}
}
}
}

private void label4_Click(object sender, EventArgs e)
{
OpenFileDialog p = new OpenFileDialog();
if (p.ShowDialog() == DialogResult.OK)
{
string flirename = p.FileName;
int page = flirename.LastIndexOf("\\");
string newname = Guid.NewGuid().ToString() + (flirename.Substring(page + 1));
tus = newname;
using (FileStream ds = new FileStream(@".\img\" + newname, FileMode.CreateNew))
{
using (Stream str = p.OpenFile())
{
str.CopyTo(ds);
str.Flush();
pictureBox1.ImageLocation = (@".\img\" + newname).ToString();
}
}
}
}

private void button2_Click(object sender, EventArgs e)
{
stuModel m = new stuModel();
m.Names = textBox1.Text;
m.Price = Convert.ToInt32(textBox2.Text);
m.Typeid = Convert.ToInt32(comboBox1.SelectedValue);
m.Imgname = tus;
Uri uri = new Uri("http://localhost:8231/");
HttpClient client = new HttpClient();
client.BaseAddress = uri;
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
HttpContent cont = new StringContent(JsonConvert.SerializeObject(m));
cont.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");

HttpResponseMessage mesa = client.PostAsync("actionApi/showApi/add", cont).Result;
if (mesa.IsSuccessStatusCode)
{
var pp = mesa.Content.ReadAsStringAsync().Result;
if (Convert.ToInt32(pp) > 0)
{
MessageBox.Show("添加成功");
this.Close();
}
else
{
MessageBox.Show("添加失败");
}

}
}
}
}

修改

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsDB2
{
public partial class xiu : Form
{
public xiu()
{
InitializeComponent();
}
string ids = "";
void xia()
{
Uri uri = new Uri("http://localhost:8231/");
HttpClient client = new HttpClient();
client.BaseAddress = uri;
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage mesa = client.GetAsync("actionApi/showApi/xia").Result;
if (mesa.IsSuccessStatusCode)
{
var p = mesa.Content.ReadAsStringAsync().Result;
var js = JsonConvert.DeserializeObject<List<stuType>>(p);
comboBox1.DisplayMember = "TypeName";
comboBox1.ValueMember = "Typeid";
comboBox1.DataSource = js;
}
}
public xiu(int id)
{
InitializeComponent();
Uri uri = new Uri("http://localhost:8231/");
HttpClient client = new HttpClient();
client.BaseAddress = uri;
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage mesa = client.GetAsync("actionApi/showApi/dan?id=" + id).Result;
if (mesa.IsSuccessStatusCode)
{
var p = mesa.Content.ReadAsStringAsync().Result;
var js = JsonConvert.DeserializeObject<List<stuModel>>(p).FirstOrDefault();
textBox1.Text = js.Names;
textBox2.Text = js.Price.ToString();
comboBox1.Text = js.TypeName;
pictureBox1.ImageLocation = (@".\img\" + js.Imgname).ToString();
ids = id.ToString();

}

}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog p = new OpenFileDialog();
if (p.ShowDialog() == DialogResult.OK)
{
string flirename = p.FileName;
int page = flirename.LastIndexOf("\\");
string newname = Guid.NewGuid().ToString() + (flirename.Substring(page + 1));
using (FileStream ds = new FileStream(@".\img\" + newname, FileMode.CreateNew))
{
using (Stream str = p.OpenFile())
{
str.CopyTo(ds);
str.Flush();

stuModel m = new stuModel();
m.Names = textBox1.Text;
m.Price = Convert.ToInt32(textBox2.Text);
m.Typeid = Convert.ToInt32(comboBox1.SelectedValue);
m.Imgname = newname;
m.ID =Convert.ToInt32(ids);
Uri uri = new Uri("http://localhost:8231/");
HttpClient client = new HttpClient();
client.BaseAddress = uri;
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
HttpContent cont = new StringContent(JsonConvert.SerializeObject(m));
cont.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");

HttpResponseMessage mesa = client.PutAsync("actionApi/showApi/xiu", cont).Result;
if (mesa.IsSuccessStatusCode)
{
var pp = mesa.Content.ReadAsStringAsync().Result;
if (Convert.ToInt32(pp) > 0)
{
MessageBox.Show("修改成功");
this.Close();
}
else
{
MessageBox.Show("修改失败");
}
}
pictureBox1.ImageLocation = (@".\img\" + newname).ToString();
}
}
}
}

private void xiu_Load(object sender, EventArgs e)
{
xia();
}
}
}

分页

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace WindowsDB2
{
public partial class fen : Form
{
public fen()
{
InitializeComponent();
}
int count = 0;
int PageIndex = 0;
int PageSize = 4;
void Bind(int PageIndex,string sql)
{
MySqlParameter[] app = new MySqlParameter[] { (new MySqlParameter("@Exstr", MySqlDbType.VarChar, 200)), new MySqlParameter("@PageIndex", MySqlDbType.Int32),new MySqlParameter("@PageSize", MySqlDbType.Int32) };
app[0].Value = "";
app[0].Direction = ParameterDirection.Input;
app[1].Value = PageIndex;
app[1].Direction = ParameterDirection.Input;
app[2].Value = PageSize;
app[2].Direction = ParameterDirection.Input;
DataSet ds = new DAL.stuDAL().show("P_Lianxi", app);
dataGridView1.DataSource = ds.Tables[0];
}

private void fen_Load(object sender, EventArgs e)
{
count = new DAL.stuDAL().cou();
PageIndex = (int)(Math.Ceiling(Convert.ToDouble(count) / PageSize));
for (int i = 1; i <=PageIndex; i++)
{
comboBox1.Items.Add(i);
}
comboBox1.Text = "1";
Bind(0, "");
}
/// <summary>
/// 首页
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button1_Click(object sender, EventArgs e)
{
comboBox1.Text = "1";
Bind(0, "");
}
/// <summary>
/// 尾页
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button4_Click(object sender, EventArgs e)
{
var row = (int)(Math.Ceiling(Convert.ToDouble(count) / PageSize));
Bind((row - 1) * 4, "");
comboBox1.Text = row.ToString();
}
/// <summary>
/// 下一页
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button2_Click(object sender, EventArgs e)
{
int page = Convert.ToInt32(comboBox1.Text);
PageIndex = (int)(Math.Ceiling(Convert.ToDouble(count) / PageSize));
if (page < PageIndex)
{
comboBox1.Text = (page + 1).ToString();
Bind((Convert.ToInt32(comboBox1.Text) - 1) * 4, "");

}
}
/// <summary>
/// 上一页
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button3_Click(object sender, EventArgs e)
{
int page = Convert.ToInt32(comboBox1.Text);

if (page!=1)
{
comboBox1.Text = (page -1).ToString();
Bind((Convert.ToInt32(comboBox1.Text) - 1) * 4, "");

}
}
}
}

分页的个数

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;
using System.Data;
namespace DAL
{
public class stuDAL
{
public MySqlConnection conn = new MySqlConnection("database = 'lianxi'; data source = 'localhost'; user id = 'root'; password='1234';charset='utf8';pooling=true");
public DataSet show(string name, params MySqlParameter[] par)
{
MySqlCommand cmd = new MySqlCommand(name,conn);
cmd.CommandType = CommandType.StoredProcedure;
DataSet ds = new DataSet();
MySqlDataAdapter data = new MySqlDataAdapter();
if (par == null)
{
return null;
}
foreach (MySqlParameter item in par)
{
cmd.Parameters.Add(item);
}
conn.Open();
cmd.ExecuteNonQuery();
data.SelectCommand = cmd;
data.Fill(ds, name);
data.Dispose();
conn.Close();
conn.Dispose();
return ds;

}
public int cou()
{
string sql = " SELECT COUNT(1) from lianxiinfo ";
conn.Open();
MySqlCommand cmd = new MySqlCommand(sql, conn);
object i = cmd.ExecuteScalar();
conn.Close();
return Convert.ToInt32(i);
}
}
}

API

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Model;
namespace WebApplicationDB2.Controllers
{
public class showApiController : ApiController
{
/// <summary>
/// 显示全部
/// </summary>
/// <returns></returns>
// GET: api/showApi
[HttpGet]
public List<stuModel> show(string name = "", int type = 1)
{
var p = new BLL.stuBLL().show(name,type);
return p.ToList();
}
/// <summary>
/// 显示下拉
/// </summary>
/// <returns></returns>
[HttpGet]
public List<stuType> xia()
{
var p = new BLL.stuBLL().xia();
return p.ToList();
}
/// <summary>
/// 一条数据
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[HttpGet]
public List<stuModel> dan(int id)
{
var p = new BLL.stuBLL().dan(id);
return p.ToList();
}
/// <summary>
/// 添加
/// </summary>
/// <param name="m"></param>
/// <returns></returns>
// GET: api/showApi/5
[HttpPost]
public int add(stuModel m)
{
var p = new BLL.stuBLL().add(m);
return p;
}
/// <summary>
/// 删除
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[HttpDelete]
public int shan(string id)
{
var p = new BLL.stuBLL().shan(id);
return p;
}
/// <summary>
/// 修改
/// </summary>
/// <param name="m"></param>
/// <returns></returns>
[HttpPut]
public int xiu(stuModel m)
{
var p = new BLL.stuBLL().xiu(m);
return p;
}
}
}

 配置

config.Routes.MapHttpRoute(
name: "actionApi",
routeTemplate: "actionApi/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);

转载于:https://www.cnblogs.com/net520/p/7860833.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值