winform导入导出excel,后台动态添加控件

思路:

导入:

1,初始化一个OpenFileDialog类 (OpenFileDialog fileDialog = new OpenFileDialog();)

2, 获取用户选择文件的后缀名(string extension = Path.GetExtension(fileDialog.FileName).ToLower();),并设置允许后缀文件名;

3,NPOI转datetable,遍历tatetable转成实体类列表并入库;

导出:

1, 创建提示用户保存类,SaveFileDialog saveFileDialog = new SaveFileDialog(),设置允许导出文件名,对话框显示信息等属性;

2,saveFileDialog.FileName.Length>0,sql转datetable,NPOI创建文件(设置保存路径 saveFileDialog.FileName)

动态添加控件注意:

1,在panal添加对应控件,便于数据太多可以下拉(AutoScroll=true);

2,设置new Point(x,y)坐标位置,控件大小调整;特别是坐标不好处理,现在页面上设置排版,并记录x,y 记录;

3,给与对应控件添加响应事件(如双击全选等等)

4,保存时后台查找控件对应值,winform没有webform的findcontrol方法,故网上找到帮助类(如下),但原理一样都是从对应Control下查找已添加类,注意动态添加控件时,命名需有规则,便于查找:

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms; namespace webfrom.common
{
public static class ControlUtil
{
/// <summary>
/// 按名称查找控件
/// </summary>
/// <param name="parentControl">查找控件的父容器控件</param>
/// <param name="findCtrlName">查找控件名称</param>
/// <returns>若没有查找到返回NULL</returns>
public static Control FindControl(this Control parentControl, string findCtrlName)
{
Control _findedControl = null;
if (!string.IsNullOrEmpty(findCtrlName) && parentControl != null)
{
foreach (Control ctrl in parentControl.Controls)
{
if (ctrl.Name.Equals(findCtrlName))
{
_findedControl = ctrl;
break;
}
}
}
return _findedControl;
}
/// <summary>
/// 将Control转换某种控件类型
/// </summary>
/// <typeparam name="T">控件类型</typeparam>
/// <param name="control">Control</param>
/// <param name="result">转换结果</param>
/// <returns>若成功则返回控件;若失败则返回NULL</returns>
public static T Cast<T>(this Control control, out bool result) where T : Control
{
result = false;
T _castCtrl = null;
if (control != null)
{
if (control is T)
{
try
{
_castCtrl = control as T;
result = true;
}
catch (Exception ex)
{
result = false;
}
}
}
return _castCtrl;
}
} //public class comBoBoxEx : System.Windows.Forms.ComboBox
//{
// public bool isWheel = false;
// public string strComB = null;
// protected override void OnMouseWheel(System.Windows.Forms.MouseEventArgs e)
// {
// strComB = Text;
// isWheel = true;
// } // protected override void OnMouseDown(System.Windows.Forms.MouseEventArgs e)
// {
// base.OnMouseDown(e);
// isWheel = false; // } // protected override void OnTextChanged(EventArgs e)
// {
// base.OnTextChanged(e);
// if (isWheel)
// {
// Text = strComB;
// }
// }
//}
}

其他:

鼠标滚动,禁用;窗口置顶;

所有后台代码:

 using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using webframework.common;
using System.Collections;
using System.IO;
using webfrom.common;
using System.Text.RegularExpressions;
using webfrom.bll;
using webfrom.model;
using MySql.Data.MySqlClient;
using System.Data.SqlClient; namespace webfrom.trip
{
public partial class tripmain : Form, IMessageFilter
{
//当前登陆用户
public string Username { get; set; }
//乘客人数
public int PsgCount { get; set; }
//订单ID
public string OrderID { get; set; }
//tt订单号
public string OrderNO { get; set; }
//平台id
public string orderFrom { get; set; }
//快递单号
public string ExpNo { get; set; } public tripmain()
{
InitializeComponent();
}
public bool PreFilterMessage(ref Message m)
{
if (m.Msg == )
{
return true;
}
else
{
return false;
}
}
//导入
private void btnimport_Click(object sender, EventArgs e)
{
lbl_msg.Text = "";
//初始化一个OpenFileDialog类
OpenFileDialog fileDialog = new OpenFileDialog();
//判断用户是否正确的选择了文件
if (fileDialog.ShowDialog() == DialogResult.OK)
{
//获取用户选择文件的后缀名
string extension = Path.GetExtension(fileDialog.FileName).ToLower();
//声明允许的后缀名
string[] str = new string[] { ".xls", ".xlsx", ".csv" };
if (!((IList)str).Contains(extension))
{
//MessageBox.Show("仅能导入xls,xlsx,csv文件!");
lbl_msg.Text = "提示信息:仅能导入xls,xlsx,csv文件!";
}
else
{
DataTable dt = new DataTable();
switch (extension)
{
case ".xlsx":
dt = common.ExcelHelper.ExcelToTableForXLSX(fileDialog.FileName);
break;
case ".xls":
dt = common.ExcelHelper.GetExcelDataAsTableNPOI(fileDialog.FileName);
break;
case ".csv":
dt = common.CSVUtil.getCsvDataByTitle(fileDialog.FileName, "业务单号", null);
break;
default:
break;
}
if (dt.Rows.Count > )
{
int error = ;
int count = ;
try
{
List<modelt_printexpress> list = new List<modelt_printexpress>();
modelt_printexpress m;
DateTime dtnow = DateTime.Now;
string orderid = string.Empty; foreach (DataRow dr in dt.Rows)
{
count++;
orderid = dr["业务单号"].ToString().Trim();
if (string.IsNullOrEmpty(orderid))
continue;
m = new modelt_printexpress();
#region model赋值
m.expcompany = dr["物流公司"].ToString().Trim();
m.busno = dr["业务单号"].ToString().Trim();//对应国内tt订单号
m.expno = dr["运单号"].ToString().Trim();
m.fworkaddress = dr["寄件单位"].ToString().Trim();
m.fname = dr["寄件人姓名"].ToString().Trim();
m.ftelno = dr["寄件人电话"].ToString().Trim();
m.fmobileno = dr["寄件人手机"].ToString().Trim();
m.fprovince = dr["寄件人省"].ToString().Trim();
m.fcity = dr["寄件人市"].ToString().Trim();
m.fregion = dr["寄件区/县"].ToString().Trim();
m.faddress = dr["寄件人地址"].ToString().Trim();
m.fpostcode = dr["寄件人邮编"].ToString().Trim();
m.tname = dr["收件人姓名"].ToString().Trim();
m.ttelno = dr["收件人电话"].ToString().Trim();
m.tmobileno = dr["收件人手机"].ToString().Trim();
m.tprovince = dr["收件省"].ToString().Trim();
m.tcity = dr["收件市"].ToString().Trim();
m.tregion = dr["收件区/县"].ToString().Trim();
m.taddress = dr["收件人地址"].ToString().Trim();
m.tpostcode = dr["收件邮政编码"].ToString().Trim();
m.exppay = StringUtils.StrToDecimal(dr["运费"].ToString().Trim(), );
m.orderprice = StringUtils.StrToDecimal(dr["订单金额"].ToString().Trim(), );
m.itemname = dr["商品名称"].ToString().Trim();
m.itemcode = dr["商品编码"].ToString().Trim();
m.itemattribute = dr["销售属性"].ToString().Trim();
m.itemprice = StringUtils.StrToDecimal(dr["商品金额"].ToString().Trim(), );
m.itemacount = StringUtils.StrToInt(dr["数量"].ToString().Trim(), );
m.leavemsg = dr["留言"].ToString().Trim();
m.note = dr["备注"].ToString().Trim();
m.operater = this.Username;
m.creattime = dtnow;
#endregion
list.Add(m);
}
string msg = string.Empty;
new bllprintexpress().InsertList(list, Config.CONSQL_172_16_6_1_WRITE, ref msg);
//MessageBox.Show("数据导入完毕【文件总数:" + dt.Rows.Count + " 导入" + msg + "--未匹配tt订单号:" + error + "】");
lbl_msg.Text = "提示信息:" + "数据导入完毕【文件总数:" + dt.Rows.Count + " 导入" + msg + "--未匹配tt订单号:" + error + "】"; }
catch (Exception ex)
{
//MessageBox.Show("导入数据报错:" + ex.Message);
lbl_msg.Text = "提示信息:" + "导入数据报错:" + ex.Message;
}
}
else
{
//MessageBox.Show("您选择的文件报表中没有数据");
lbl_msg.Text = "提示信息:" + "您选择的文件报表中没有数据";
}
}
}
}
//导出
private void btnexport_Click(object sender, EventArgs e)
{
try
{
lbl_msg.Text = "";
DateTime dtbegin = Convert.ToDateTime(dtpbegin.Value.ToString("yyyy-MM-dd"));
DateTime dtend = Convert.ToDateTime(dtpend.Value.ToString("yyyy-MM-dd"));
if ((dtend - dtbegin).Days > )
{
//MessageBox.Show("航班日期跨度不能超过30天");
lbl_msg.Text = "提示信息:" + "航班日期跨度不能超过30天";
dtpbegin.Focus();
return;
}
if (dtend < dtbegin)
{
//MessageBox.Show("航班开始日期不能大于结束日期");
lbl_msg.Text = "提示信息:" + "航班开始日期不能大于结束日期";
dtpbegin.Focus();
return;
} SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "导出Excel (*.xls)|*.xls";
saveFileDialog.FilterIndex = ;
saveFileDialog.RestoreDirectory = true;
saveFileDialog.CreatePrompt = true;
saveFileDialog.Title = "导出文件保存路径";
saveFileDialog.ShowDialog();
string strName = saveFileDialog.FileName;
if (strName.Length != )
{
string sql = "SELECT o.id orderid ,o.orderNo,jd.receiver,jd.receiverPhone,jd.postCode,jd.postAddress " +
"FROM t_order AS o " +
"LEFT JOIN t_journey AS jo ON o.id = jo.orderId " +
"LEFT JOIN t_journeypassenger AS jp ON jo.id = jp.journeyId " +
"LEFT JOIN t_passenger AS p ON jp.passengerId = p.id " +
"LEFT JOIN t_travel AS tr ON jp.id = tr.journeyPassengerId " +
"RIGHT JOIN t_journeydetail AS jd ON o.id = jd.orderId " +
"WHERE 1=1 AND o.orderFrom=1 " +
"AND (jp.pTikState IS NULL OR jp.pTikState!=1) " +
"AND jd.postAddress <>'' " +
"AND (o.orderState=1 OR o.orderState=3 OR o.orderState=7) " +
"AND jo.takeoffDate >='" + dtbegin.ToString("yyyy-MM-dd") + "' " +
"AND jo.takeoffDate <='" + dtend.ToString("yyyy-MM-dd") + "' " +
"AND (tr.printState IS NULL OR tr.printState=0) " +
"AND jd.isTra=1 AND (jd.isTra=1 AND jd.isTraKf <> 0) " +
//"AND jd.isTra=1 AND ((jd.isTra=1 AND jd.isTraKf <> 0) or jd.isTraKf=1) " +
//" and (jd.traAddress<>'' or jd.isTraKf=1) orderFrom ==0" +
"GROUP BY orderid";
DataTable dt = webframework.common.MySqlHelper.ExecuteDataSet(webframework.common.MySqlHelper.ConnectionString, CommandType.Text, sql).Tables[];
if (dt != null && dt.Rows.Count > )
{
string strids = string.Empty;
string straddress = string.Empty;
string mobilecode = string.Empty;
string phonecode = string.Empty;
string postcode = string.Empty;
string address = string.Empty; DataTable dtnew = new DataTable();
//dtnew.Columns.Add("姓名", typeof(string));
//dtnew.Columns.Add("订单ID", typeof(string));
//dtnew.Columns.Add("联系单位", typeof(string));
//dtnew.Columns.Add("联系地址", typeof(string));
//dtnew.Columns.Add("手机号码", typeof(string));
//dtnew.Columns.Add("电话号码", typeof(string));
//dtnew.Columns.Add("邮编", typeof(string)); dtnew.Columns.Add("业务单号", typeof(string));
dtnew.Columns.Add("收件人姓名", typeof(string));
dtnew.Columns.Add("收件人手机", typeof(string));
dtnew.Columns.Add("收件人地址", typeof(string));
dtnew.Columns.Add("品名", typeof(string));
dtnew.Columns.Add("数量", typeof(string));
dtnew.Columns.Add("备注", typeof(string));
foreach (DataRow item in dt.Rows)
{
if (!strids.Contains(item["orderid"].ToString().Trim()))
{
strids += item["orderid"].ToString().Trim() + ",";
straddress = item["postAddress"].ToString().Trim().TrimEnd('-').TrimStart('-');
var arr = straddress.Split('-');
if (arr.Length < )
continue; mobilecode = item["receiverPhone"].ToString().Trim();
if (string.IsNullOrEmpty(mobilecode))
{
if (Regex.IsMatch(straddress, @"-1\d{10}", RegexOptions.Multiline))
mobilecode = new Regex(@"-1\d{10}", RegexOptions.Multiline).Matches(straddress)[].Groups[].Value.Replace("-", "");
else
mobilecode = arr[arr.Length - ];
} if (Regex.IsMatch(straddress, @"-\d{4}-\d{7,8}|-\d{3}-\d{8}", RegexOptions.Multiline))
phonecode = new Regex(@"-\d{4}-\d{7,8}|-\d{3}-\d{8}", RegexOptions.Multiline).Matches(straddress)[].Groups[].Value.TrimStart('-');
else
phonecode = ""; if (Regex.IsMatch(straddress, @"-\d{6}-", RegexOptions.Multiline))
postcode = new Regex(@"-\d{6}-", RegexOptions.Multiline).Matches(straddress)[].Groups[].Value.Replace("-", "");
else
postcode = arr[arr.Length - ]; address = straddress.Substring(straddress.IndexOf('-') + ).Replace(mobilecode, "").Replace(postcode, "");
address = (phonecode.Length > ? address.Replace(phonecode, "") : address).Replace("-", " ");
DataRow dtrow = dtnew.NewRow();
////姓名 订单ID 联系单位 联系地址 手机号码 电话号码 邮编
//dtrow["姓名"] = item["receiver"].ToString().Trim();
//dtrow["订单ID"] = item["orderid"].ToString().Trim();
//dtrow["联系单位"] = "天泰";
//dtrow["手机号码"] = mobilecode;
//dtrow["电话号码"] = phonecode;
//dtrow["邮编"] = postcode;
//dtrow["联系地址"] = address; //业务单号 收件人姓名 收件人手机 收件人地址 品名 数量 备注
dtrow["业务单号"] = item["orderid"].ToString().Trim();
dtrow["收件人姓名"] = item["receiver"].ToString().Trim();
dtrow["收件人手机"] = mobilecode;
dtrow["收件人地址"] = address;
dtrow["品名"] = "票务";
dtrow["数量"] = "";
dtrow["备注"] = item["orderNo"].ToString().Trim() + "||" + item["postAddress"].ToString().Trim();
dtnew.Rows.Add(dtrow);
} } NewExcelHelper.ExportExcel(dtnew, strName, "联系人数据" + dtbegin.ToString("yyyyMMdd") + "_" + dtend.ToString("yyyyMMdd"));
//MessageBox.Show("导出数据成功(路径:" + strName);
lbl_msg.Text = "提示信息:" + "导出数据成功(路径:" + strName;
}
}
}
catch (Exception ex)
{
//MessageBox.Show("导出数据出错:" + ex.Message);
lbl_msg.Text = "提示信息:" + "导出数据出错:" + ex.Message;
}
} private void txtbarcode_TextChanged(object sender, EventArgs e)
{
lbl_msg.Text = "";
if (txtbarcode.Text.Trim().Length > )
{
this.PsgCount = ;
this.OrderID = "";
this.OrderNO = "";
this.orderFrom = "";
this.ExpNo = "";
//gbdetail.Text = "扫条码快递号对应TT订单明细";
string sql1 = "select busno,expno from t_printexpress where expno=@expno";
SqlParameter[] parameters = { new SqlParameter("@expno", SqlDbType.VarChar, ) };
parameters[].Value = txtbarcode.Text.Trim();
DataTable dtp = SqlHelper.ExecuteDataTable(Config.CONSQL_172_16_6_1_WRITE, CommandType.Text, sql1, parameters);
if (dtp != null && dtp.Rows.Count > )
{
OrderID = dtp.Rows[]["busno"].ToString();
ExpNo = dtp.Rows[]["expno"].ToString();
if (!string.IsNullOrEmpty(OrderID))
{
BindData(OrderID);
}
}
else
{
gbdetail.Visible = false;
pldetail.Controls.Clear();
}
}
else if (txtbarcode.Text.Trim().Length == )
{
gbdetail.Visible = false;
pldetail.Controls.Clear();
}
}
private void BindData(string orderid)
{
this.OrderNO = "";
this.orderFrom = "";
txtorderid.Text = "";
txtorderno.Text = "";
//gbdetail.Text = "扫条码快递号对应TT订单明细";
string sql = "SELECT o.id,o.orderfrom,o.bank,o.shopName,o.returnDate,o.tbRate,o.orderNo,o.cNo,o.outDate,o.outTime,o.totalBrokerage,o.orderState,o.payState,o.policyType,o.totalPrice,o.tradeNo,o.impUser,o.impUserId,o.otherOrderSum,o.otherpolicysource,o.otherpolicycode, o.orderFrom,o.imDate,o.imTime,o.platformFlag,o.ispnrpnamepiny,isCheckedData,o.ext1,o.createTime,lk.id AS k_id ,lk.orderno AS k_orderno,lk.orderid AS k_orderid , lk.name AS k_name,lk.phone AS k_phone,lk.preparePhone,lk.email,lk.postAddress, od.id AS od_id , od.needInsurance,od.needps,od.backnote,od.xcdprice,jo.id AS j_id,jo.orderid AS jo_orderid, jo.id AS j_id , jo.pnr AS jo_pnr,jo.flightNo,jo.startCity,jo.reachCity,jo.takeoffDate,jo.takeoffTime,jo.reachTime,jo.sailType,jo.policyType AS jo_policytype,jo.seat,jo.lastOpenCabin,jo.cBasePrice,jo.bigpnr,jo.journeypoint,jo.journeystate,jo.reachdate,jo.journeyIsOutTicket,jo.journeyOtherOrderNo,jo.journeyIsOutTicket,jo.journeyOtherOrderNo,jo.journeyPlatformFlag,jo.journeyTradeNo,jo.journeyOtherOrderSum,jo.journeyRemark,jo.journeyTotalTax,jo.cwebprice,jo.shoppingprice,jo.isshareflight,jo.lowcabinSeat,jo.lowcabinPnr,jo.goType,jp.id AS jp_id ,jp.journeyId,jp.pnr,jp.insureCount,jp.insurePrice,jp.tktNo1,jp.tktPrice,jp.backPoint,jp.isOpen AS isopen,jp.purchPrice,jp.payPurchPrice,jp.actualPrice,jp.sellPrice,jp.tax,jp.myc,jp.purchPalse,jp.TbCommission,jp.payCard,jp.reciptWay,jp.otherTax,jp.otherMyc,jp.pTikState,jp.jpstatus,jp.outcode,jp.thirdOrderno,jp.delayinsurePrice,jp.delayinsureCount,jp.bigpnr AS jp_bigpnr,p.id AS p_id,p.name AS p_name, p.ptype, p.email AS p_email, p.phone AS p_phone, p.idCard, p.birthday, p.papersType, p.nationality, p.mun,jd.id AS jd_id,jd.orderid AS jd_orderId,jd.orderno AS jd_orderNo,jd.journeyId AS jd_journeyid,jd.isReturnTra,jd.isTra,jd.traCostPrice,jd.traPrice,jd.postaddress AS jd_postAddress,jd.postCode,jd.receiver,jd.receiverPhone,jd.traAddress,jd.isInsure,jd.sendWay,jd.isTraKf,jd.isInsureKf,jd.insureRmkKf,jd.traRmkKf,jd.expressFee,jd.tradeNO AS jd_tradeNO,t.travelNo,t.printState,t.printType,t.postWay,t.postNo " +
"FROM t_order o LEFT JOIN t_orderdetail od ON o.id=od.id " +
"LEFT JOIN t_linkman lk ON o.id=lk.orderId " +
"LEFT JOIN t_journey jo ON o.id=jo.orderId " +
"LEFT JOIN t_journeypassenger jp ON jp.journeyId=jo.id " +
"LEFT JOIN t_passenger p ON jp.passengerId = p.id " +
"LEFT JOIN t_journeydetail jd ON jd.orderid = o.id " +
"LEFT JOIN t_travel t on o.id=t.orderId and t.journeyPassengerId=jp.id " +
"WHERE (jp.pTikState IS NULL OR jp.pTikState!=1) " +
"AND o.id=" + orderid;
DataTable dt = webframework.common.MySqlHelper.ExecuteDataSet(webframework.common.MySqlHelper.ConnectionString, CommandType.Text, sql).Tables[]; string sqltemp = "select tripno,printstate,printtype,postway from t_tripexpress where tktno='{0}'";
string tripno = "";
string printstate = "";
string printtype = "";
string postway = "";
string expno = "";
DataTable dttripno = new DataTable();
if (dt != null && dt.Rows.Count > )
{
pldetail.Controls.Clear();
PsgCount = dt.Rows.Count;
DataRow row = dt.Rows[];
//lblflightconnect.Text = "航班号: HO1179 承运人: HO 起始地: PVG 目的地: HRB 日期(起): 2016-10-21 时间(起): 08:30:00 航程类型: S 舱位: P \r\n联系人:xxx 联系电话:1234567890";
lblflightconnect.Text = string.Format("航班号:{0} 承运人:{1} 起始地:{2} 目的地:{3} 日期(起):{4} 时间(起): {5} 航程类型:{6} 舱位:{7} \r\n\r\n联系人:{8} 联系地址:{9}", row["flightNo"].ToString().Trim(), row["flightNo"].ToString().Trim().Substring(, ), row["startCity"].ToString().Trim(), row["reachCity"].ToString().Trim(), (string.IsNullOrEmpty(row["takeoffDate"].ToString().Trim()) ? "" : Convert.ToDateTime(row["takeoffDate"].ToString().Trim()).ToString("yyyy-MM-dd")), row["takeoffTime"].ToString().Trim(), row["sailType"].ToString().Trim(), row["seat"].ToString().Trim(), row["receiver"].ToString().Trim(), row["jd_postAddress"].ToString().Trim());
int num = ;
Label lbl = new Label();
int x = ;
int y = ;
int rowwidth = ;
TextBox txt = new TextBox();
ComboBox cbb = new ComboBox();
foreach (DataRow item in dt.Rows)
{
this.OrderNO = item["orderNo"].ToString().Trim();
this.orderFrom = item["orderfrom"].ToString().Trim();
//第一行
lbl = new Label();
lbl.Width = ;
lbl.Height = ;
lbl.ForeColor = Color.Blue;
lbl.Location = new Point(x, y + rowwidth * num);
lbl.Name = "lblpsgdes" + num;
lbl.Text = string.Format("退票状态:{0} 类型:{1} 票面:{2} 采购价(实):{3} 销售价:{4} 机建:{5} 燃油:{6} 实收金额:{7}\r\n\r\n", GetTikStateDesc(item["pTikState"]), GetPtypeDesc(item["ptype"]), item["sellprice"].ToString().Trim(), item["purchprice"].ToString().Trim(), item["actualprice"].ToString().Trim(), item["tax"].ToString().Trim(), item["myc"].ToString().Trim(), StringUtils.StrToDecimal(item["actualprice"].ToString().Trim(), ) + StringUtils.StrToDecimal(item["tax"].ToString().Trim(), ) + StringUtils.StrToDecimal(item["myc"].ToString().Trim(), ));
pldetail.Controls.Add(lbl);
//第二行
lbl = new Label();
lbl.Location = new Point(, (y * + ) + rowwidth * num);//18,50
lbl.Name = "lblpname" + num;
lbl.Text = "姓名:";
lbl.Width = ;
lbl.Height = ;
pldetail.Controls.Add(lbl);
txt = new TextBox();
txt.Location = new Point(x * + , (y * + ) + rowwidth * num);//78.46
txt.Name = "txtpname" + num;
txt.Text = item["p_name"].ToString().Trim();
txt.MouseDoubleClick += txt_MouseDoubleClick;
txt.ReadOnly = true;
txt.Width = ;
txt.Height = ;
pldetail.Controls.Add(txt); lbl = new Label();
lbl.Location = new Point(x * + + , (y * + ) + rowwidth * num);//188+6,50
lbl.Name = "lblidCard" + num;
lbl.Text = "证件号:";
lbl.Width = - ;
lbl.Height = ;
pldetail.Controls.Add(lbl);
txt = new TextBox();
txt.Location = new Point(x * + - - , (y * + ) + rowwidth * num);//244-12-5.46
txt.Name = "txtidCard" + num;
txt.Text = item["idCard"].ToString().Trim();
txt.MouseDoubleClick += txt_MouseDoubleClick;
txt.ReadOnly = true;
txt.Width = ;
txt.Height = ;
pldetail.Controls.Add(txt); lbl = new Label();
lbl.Location = new Point(x * + + , (y * + ) + rowwidth * num);//364+6,50
lbl.Name = "lbltktNo1" + num;
lbl.Text = "票号:";
lbl.Width = ;
lbl.Height = ;
pldetail.Controls.Add(lbl);
txt = new TextBox();
txt.Location = new Point(x * + , (y * + ) + rowwidth * num);//428.46
txt.Name = "txttktNo1" + num;
txt.Text = item["tktNo1"].ToString().Trim();
txt.MouseDoubleClick += txt_MouseDoubleClick;
txt.ReadOnly = true;
txt.Width = ;
txt.Height = ;
pldetail.Controls.Add(txt); tripno = item["travelNo"].ToString().Trim();
if (string.IsNullOrEmpty(tripno) && item["tktNo1"].ToString().Trim().Length > )
{
dttripno = SqlHelper.ExecuteDataTable(Config.CONSQL_172_16_6_1_WRITE, CommandType.Text, string.Format(sqltemp, item["tktNo1"].ToString().Trim()));
if (dttripno != null && dttripno.Rows.Count > )
{
tripno = dttripno.Rows[]["tripno"].ToString();
}
}
lbl = new Label();
lbl.Location = new Point(x * + + , (y * + ) + rowwidth * num);//534+4,50
lbl.Name = "lbltravelNo" + num;
lbl.Text = "行程单号:";
lbl.Width = ;
lbl.Height = ;
pldetail.Controls.Add(lbl);
txt = new TextBox();
txt.Location = new Point(x * + + , (y * + ) + rowwidth * num);//590+6.46
txt.Name = "txttravelNo" + num;
txt.MouseDoubleClick += txt_MouseDoubleClick;
txt.Text = tripno;
txt.BackColor = Color.FloralWhite;
txt.Width = ;
txt.Height = ;
pldetail.Controls.Add(txt); //打印状态 printState 、打印方式 printType、邮寄方式 postWay、邮寄单号 postNo、行程单号 travelNo
//第三行
lbl = new Label();
lbl.Location = new Point(x, (y * + ) + rowwidth * num);//18,78
lbl.Name = "lblprintState" + num;
lbl.Text = "打印状态:";
lbl.Width = ;
lbl.Height = ;
pldetail.Controls.Add(lbl);
printstate = GetPrintState(item["printState"].ToString().Trim());
cbb = new ComboBox();
cbb.DropDownStyle = ComboBoxStyle.DropDownList;
cbb.Width = ;
cbb.Height = ;
cbb.Name = "cbbprintState" + num;
cbb.Location = new Point(x * + , (y * + ) + rowwidth * num);//78.72
BindCbbPrintState(ref cbb, printstate, (dttripno != null && dttripno.Rows.Count > ) ? dttripno.Rows[]["printstate"].ToString() : "");
if (num == )
cbb.SelectedIndexChanged += cbb_SelectedIndexChanged;
pldetail.Controls.Add(cbb); lbl = new Label();
lbl.Location = new Point(x * + + , (y * + ) + rowwidth * num);//188+6,78
lbl.Name = "lblprintType" + num;
lbl.Text = "打印方式:";
lbl.Width = ;
lbl.Height = ;
pldetail.Controls.Add(lbl);
printtype = GetPrintType(item["printType"].ToString().Trim());
cbb = new ComboBox();
cbb.DropDownStyle = ComboBoxStyle.DropDownList;
cbb.Location = new Point(x * + - , (y * + ) + rowwidth * num);//244-12.72
cbb.Width = ;
cbb.Height = ;
cbb.Name = "cbbprintType" + num;
BindCbbPrintType(ref cbb, printtype, (dttripno != null && dttripno.Rows.Count > ) ? dttripno.Rows[]["printtype"].ToString() : "");
if (num == )
cbb.SelectedIndexChanged += cbb_SelectedIndexChanged;
pldetail.Controls.Add(cbb); lbl = new Label();
lbl.Location = new Point(x * + + , (y * + ) + rowwidth * num);//364+6,78
lbl.Name = "lblpostWay" + num;
lbl.Text = "邮寄方式:";
lbl.Width = ;
lbl.Height = ;
pldetail.Controls.Add(lbl);
postway = GetPostWay(item["postWay"].ToString().Trim());
cbb = new ComboBox();
cbb.DropDownStyle = ComboBoxStyle.DropDownList;
cbb.Location = new Point(x * + , (y * + ) + rowwidth * num);//428.72
cbb.Width = ;
cbb.Height = ;
cbb.Name = "cbbpostWay" + num;
BindCbbPostWay(ref cbb, postway, (dttripno != null && dttripno.Rows.Count > ) ? dttripno.Rows[]["postway"].ToString() : "");
if (num == )
cbb.SelectedIndexChanged += cbb_SelectedIndexChanged;
pldetail.Controls.Add(cbb); expno = string.IsNullOrEmpty(item["postNo"].ToString().Trim()) ? ExpNo : item["postNo"].ToString().Trim();
lbl = new Label();
lbl.Location = new Point(x * + + , (y * + ) + rowwidth * num);//534+4,78
lbl.Name = "lblpostNo" + num;
lbl.Text = "快递单号:";
lbl.Width = ;
lbl.Height = ;
pldetail.Controls.Add(lbl);
txt = new TextBox();
txt.Location = new Point(x * + + , (y * + ) + rowwidth * num);//590+6.72
txt.Name = "txtpostNo" + num;
txt.MouseDoubleClick += txt_MouseDoubleClick;
txt.Text = expno;
txt.Width = ;
txt.Height = ;
txt.ReadOnly = true;
pldetail.Controls.Add(txt); num++;
}
//gbdetail.Text = "扫条码快递号对应TT订单明细(订单ID:" + orderid + " 订单号:" + this.OrderNO + ")";
txtorderid.Text = this.OrderID;
txtorderno.Text = this.OrderNO;
gbdetail.Visible = true;
//pldetail.Focus();
}
else
{
logclass.Info("订单ID(" + orderid + " 订单号:" + this.OrderNO + ")在tt上匹配不了数据");
}
} private void BindCbbPrintState(ref ComboBox cbb, string ttkey, string strcurrent)
{
//'打印状态(0:未打印 1:已打印 2:已退回)'
cbb.Items.Add("已打印");
cbb.Items.Add("");
cbb.Items.Add("未打印");
cbb.Items.Add("已退回");
cbb.SelectedIndex = ;
if (!string.IsNullOrEmpty(ttkey))
{
int index = ;
foreach (var item in cbb.Items)
{
if (item.ToString() == ttkey)
{
cbb.SelectedIndex = index;
cbb.Enabled = false;
break;
}
index++;
}
}
else
{
if (!string.IsNullOrEmpty(strcurrent))
{
int index = ;
foreach (var item in cbb.Items)
{
if (item.ToString() == strcurrent)
{
cbb.SelectedIndex = index;
break;
}
index++;
}
}
}
}
private string GetPrintState(string key)
{
//'打印状态(0:未打印 1:已打印 2:已退回)'
string result = "";
switch (key)
{
case "":
result = "未打印";
break;
case "":
result = "已打印";
break;
case "":
result = "已退回";
break;
default:
break;
}
return result;
} private void BindCbbPrintType(ref ComboBox cbb, string ttkey, string strcurrent)
{
//打印方式(1:创打 2:模打 3:机场打印 4;客票未使用 5:客票已退票 6:客人取消)
cbb.Items.Add("创打");
cbb.Items.Add("");
cbb.Items.Add("模打");
cbb.Items.Add("机场打印");
cbb.Items.Add("客票未使用");
cbb.Items.Add("客票已退票");
cbb.Items.Add("客人取消");
cbb.SelectedIndex = ;
if (!string.IsNullOrEmpty(ttkey))
{
int index = ;
foreach (var item in cbb.Items)
{
if (item.ToString() == ttkey)
{
cbb.SelectedIndex = index;
cbb.Enabled = false;
break;
}
index++;
}
}
else
{
if (!string.IsNullOrEmpty(strcurrent))
{
int index = ;
foreach (var item in cbb.Items)
{
if (item.ToString() == strcurrent)
{
cbb.SelectedIndex = index;
break;
}
index++;
}
}
}
}
private string GetPrintType(string key)
{
////打印方式(1:创打 2:模打 3:机场打印 4;客票未使用 5:客票已退票 6:客人取消)'
string result = "";
switch (key)
{
case "":
result = "创打";
break;
case "":
result = "模打";
break;
case "":
result = "机场打印";
break;
case "":
result = "客票未使用";
break;
case "":
result = "客票已退票";
break;
case "":
result = "客人取消";
break;
default:
break;
}
return result;
} private void BindCbbPostWay(ref ComboBox cbb, string ttkey, string strcurrent)
{
//'邮寄方式(1 公司自取 2 其它 12 韵达月结 13 韵达到付 4 汇通月结 5 汇通到付 9 顺丰到付 10 顺丰月结 11 邮政小包
cbb.Items.Add("韵达月结");
cbb.Items.Add("");
cbb.Items.Add("公司自取");
cbb.Items.Add("其它");
cbb.Items.Add("韵达到付");
cbb.Items.Add("汇通月结");
cbb.Items.Add("已打印");
cbb.Items.Add("汇通到付");
cbb.Items.Add("顺丰到付");
cbb.Items.Add("顺丰月结");
cbb.Items.Add("邮政小包");
cbb.SelectedIndex = ;
if (!string.IsNullOrEmpty(ttkey))
{
int index = ;
foreach (var item in cbb.Items)
{
if (item.ToString() == ttkey)
{
cbb.SelectedIndex = index;
cbb.Enabled = false;
break;
}
index++;
}
}
else
{
if (!string.IsNullOrEmpty(strcurrent))
{
int index = ;
foreach (var item in cbb.Items)
{
if (item.ToString() == strcurrent)
{
cbb.SelectedIndex = index;
break;
}
index++;
}
}
}
}
private string GetPostWay(string key)
{
//'邮寄方式(1 公司自取 2 其它 12 韵达月结 13 韵达到付 4 汇通月结 5 汇通到付 9 顺丰到付 10 顺丰月结 11 邮政小包
string result = "";
switch (key)
{
case "":
result = "公司自取";
break;
case "":
result = "其它";
break;
case "":
result = "韵达月结";
break;
case "":
result = "韵达到付";
break;
case "":
result = "汇通月结";
break;
case "":
result = "汇通到付";
break;
case "":
result = "顺丰到付";
break;
case "":
result = "顺丰月结";
break;
case "":
result = "邮政小包";
break;
default:
break;
}
return result;
} private void btnensure_Click(object sender, EventArgs e)
{
if (!gbdetail.Visible)
{
return;
} if (this.PsgCount > && !string.IsNullOrEmpty(this.OrderID) && !string.IsNullOrEmpty(this.Username))
{
List<modelt_tripexpress> list = new List<modelt_tripexpress>();
modelt_tripexpress m;
bool ischange = false;
string tripno = string.Empty;
string printstate = string.Empty;
string printtype = string.Empty;
string postway = string.Empty;
TextBox txt;
ComboBox cbb;
for (int i = ; i < PsgCount; i++)
{
//打印状态 printState、行程单号 travelNo 、打印方式 printType、邮寄方式 postWay、邮寄单号 postNo
txt = pldetail.FindControl("txttravelNo" + i.ToString()).Cast<TextBox>(out ischange);
tripno = txt.Text.Trim();
if (string.IsNullOrEmpty(tripno))
{
lbl_msg.Text = "提示信息:" + "第" + (i + ).ToString() + "个乘客的行程单号不能为空";
txt.Focus();
txt.SelectAll();
return;
}
cbb = pldetail.FindControl("cbbprintState" + i.ToString()).Cast<ComboBox>(out ischange);
printstate = cbb.SelectedItem.ToString();
if (string.IsNullOrEmpty(printstate))
{
lbl_msg.Text = "提示信息:" + "第" + (i + ).ToString() + "个乘客的打印状态不能为空";
cbb.Focus();
return;
}
cbb = pldetail.FindControl("cbbprintType" + i.ToString()).Cast<ComboBox>(out ischange);
printtype = cbb.SelectedItem.ToString();
if (string.IsNullOrEmpty(printtype))
{
lbl_msg.Text = "提示信息:" + "第" + (i + ).ToString() + "个乘客的打印方式不能为空";
cbb.Focus();
return;
}
cbb = pldetail.FindControl("cbbpostWay" + i.ToString()).Cast<ComboBox>(out ischange);
postway = cbb.SelectedItem.ToString();
if (string.IsNullOrEmpty(postway))
{
lbl_msg.Text = "提示信息:" + "第" + (i + ).ToString() + "个乘客的邮寄方式不能为空";
cbb.Focus();
return;
} m = new modelt_tripexpress();
m.operater = this.Username;
m.orderid = this.OrderID;
m.postway = postway;
m.printstate = printstate;
m.printtype = printtype;
m.expno = this.ExpNo;
m.tktno = pldetail.FindControl("txttktNo1" + i.ToString()).Cast<TextBox>(out ischange).Text.Trim();
m.tripno = tripno;
m.creattime = DateTime.Now;
list.Add(m);
}
string msg = string.Empty;
if (new blltripexpress().InsertList1(list, Config.CONSQL_172_16_6_1_WRITE, ref msg) > )
{
//MessageBox.Show("行程单号保存成功!");
string msg1 = "提示信息:(订单ID:" + this.OrderID + " 订单号:" + this.OrderNO + ")行程单号保存成功!";
BindData(OrderID);
txtbarcode.Text = "";
lbl_msg.Text = msg1;
}
else
{
//MessageBox.Show("添加失败");
lbl_msg.Text = "提示信息:(订单ID:" + this.OrderID + " 订单号:" + this.OrderNO + ")行程单号添加失败";
}
txtbarcode.SelectAll();
txtbarcode.Focus();
}
else
{
//MessageBox.Show("没有匹配到数据");
lbl_msg.Text = "提示信息:(订单ID:" + this.OrderID + " 订单号:" + this.OrderNO + ")行程单号没有匹配到数据";
} }
private void txt_MouseDoubleClick(object sender, MouseEventArgs e)
{
((TextBox)sender).SelectAll();
}
private string GetTikStateDesc(object item)
{
string result = "已出票";
string pTikState = item == null ? "" : item.ToString().Trim();
//pTikState 客户行程状态(0已出票 1已退票 2已改签)
switch (pTikState)
{
case "":
result = "已出票";
break;
case "":
result = "已退票";
break;
case "":
result = "已改签";
break;
default:
break;
}
return result;
}
private string GetPtypeDesc(object item)
{
string result = "成人";
string Ptype = item == null ? "" : item.ToString().Trim();
////乘机人类型(1成人2儿童3婴儿4老人)
switch (Ptype)
{
case "":
result = "成人";
break;
case "":
result = "儿童";
break;
case "":
result = "婴儿";
break;
case "":
result = "老人";
break;
default:
break;
}
return result;
}
private void tripmain_Load(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(this.Username))
{
MessageBox.Show("非法操作");
lbl_msg.Text = "提示信息:" + "非法操作";
this.Close();
}
else
{
Application.AddMessageFilter(this);
this.MouseWheel += new MouseEventHandler(pnl_MouseWheel);
dtpbegin.Value = DateTime.Now.AddDays(-);
lbl_msg.Text = "";
timer1.Interval = * * ;//毫秒为单位
timer1.Start();
gbdetail.Visible = false;
this.Text = string.Format("快递单扫描======={0},欢迎您!", this.Username); }
}
private void tripmain_KeyDown(object sender, KeyEventArgs e)
{
if (e.Control && e.KeyCode == Keys.Tab)
{
//这里写你摁下 Tab之后所要进行的动作的代码
txtbarcode.Focus();
txtbarcode.SelectAll();
}
}
//窗口置顶
private void timer1_Tick(object sender, EventArgs e)
{
this.TopMost = false;
this.BringToFront();
this.TopMost = true;
}
private void tripmain_FormClosed(object sender, FormClosedEventArgs e)
{
timer1.Stop(); if (e.CloseReason == CloseReason.WindowsShutDown)
{
//添加所需使用的代码
logclass.Debug(DateTime.Now + "【电脑关机或者被注销" + "===系统用户:" + System.Environment.UserName + "】");
}
if (e.CloseReason == CloseReason.TaskManagerClosing)
{
//添加所需使用的代码
logclass.Debug(DateTime.Now + "【任务管理器关闭" + "===系统用户:" + System.Environment.UserName + "】");
}
if (e.CloseReason == CloseReason.None)
{
//添加所需使用的代码
logclass.Debug(DateTime.Now + "【未知意外关闭" + "===系统用户:" + System.Environment.UserName + "】");
}
}
private void tripmain_FormClosing(object sender, FormClosingEventArgs e)
{
logclass.Debug("==程序关闭==");
System.Environment.Exit(System.Environment.ExitCode);
}
private void tripmain_Activated(object sender, EventArgs e)
{
txtbarcode.Focus(); //this.AcceptButton = btnensure;
} private void linkurl_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
BrowserHelper.OpenIe(string.Format("http:www.test.com?orderFrom={1}&id={0}", this.OrderID, this.orderFrom));
} private void cbb_SelectedIndexChanged(object sender, EventArgs e)
{
ComboBox cbb = ((ComboBox)sender);
bool ischange = false;
int index = cbb.SelectedIndex;
string name = cbb.Name;
int current = int.Parse(name.Substring(name.Length - ));
string tempname = name.Substring(, name.Length - ); for (int i = ; i < PsgCount; i++)
{
if (current == i)
continue;
pldetail.FindControl(tempname + i.ToString()).Cast<ComboBox>(out ischange).SelectedIndex = index;
} }
/// <summary>
/// 鼠标滚动
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void pnl_MouseWheel(object sender, MouseEventArgs e)
{
//获取光标位置
Point mousePoint = new Point(e.X, e.Y);
//换算成相对本窗体的位置
mousePoint.Offset(this.Location.X, this.Location.Y);
//判断是否在panel内
if (pldetail.RectangleToScreen(pldetail.DisplayRectangle).Contains(mousePoint))
{
//滚动
pldetail.AutoScrollPosition = new Point(, pldetail.VerticalScroll.Value - e.Delta);
}
} }
}

效果图:

winform导入导出excel,后台动态添加控件

上一篇:ASP.NET之Application、Session和Cookie的差别


下一篇:C# 扩展方法奇思妙用高级篇六:WinForm 控件选择器