private Boolean ValidateData() { Boolean result = false; if (vw.SelectType.Equals("3")) { CMessageBox.Show(CLanguage.getValue("ERROR_TYPE_NOT_SUPPORT"), "ERROR", MessageBoxButton.OK, MessageBoxImage.Error); return(false); } result = CHelper.ValidateLookup(lb_itemcode, lkup, false); if (!result) { return(result); } result = CHelper.ValidateTextBox(lb_quantity, txt_quantity, false); if (!result) { return(result); } result = CHelper.ValidateTextBox(lb_unitprice, txt_unitprice, true); if (!result) { return(result); } if ((vw.IsWhTax) && (CUtil.StringToDouble(vw.WHTaxPct) <= 0.00)) { CHelper.ShowErorMessage("", "ERROR_WH_MUST_GREATER_THAN_ZERO", null); return(false); } result = CHelper.ValidateLookup(lblProject, uProject, IsSaleOrder); if (!result) { return(result); } return(result); }
protected override void BtnOK_Click(object sender, EventArgs e) { string strDBIP = Functions.FormatString(txtDBIP.Text); string strUserName = Functions.FormatString(txtUserName.Text); string strUserPassword = Functions.FormatString(txtUserPassword.Text); //地址 if (string.IsNullOrEmpty(strDBIP) || strDBIP.Equals("")) { txtDBIP.Focus(); CMessageBox.ShowError(string.Format("请输入数据库地址!"), Config.DialogTitle); return; } //名称 if (string.IsNullOrEmpty(strUserName) || strUserName.Equals("")) { txtUserName.Focus(); CMessageBox.ShowError(string.Format("请输入数据库用户名!"), Config.DialogTitle); return; } DBLinkTestForm objModal = new DBLinkTestForm(string.Format("SERVER={0};Port={1};User ID={2};Password={3};Charset={4};Database=mysql;allow user variables=true", strDBIP, "3308", strUserName, strUserPassword, System.Text.Encoding.Default.HeaderName.ToString())); if (objModal.ShowDialog() == DialogResult.OK) { _DBSetting = new DBSetting() { DB_IP = strDBIP, DB_User = strUserName, DB_Password = strUserPassword }; this.DialogResult = DialogResult.OK; } else if (objModal.ShowDialog() == DialogResult.No) { CMessageBox.ShowError(string.Format("目的服务器配置错误,原因可能是数据库未安装或则用户名密码错误,请重新设置和排查!"), Config.DialogTitle); } else { Application.Exit(); } }
/// <summary> /// 绑定数据到列表 /// </summary> /// <param name="selNum">数据条数</param> /// <param name="sqlWhereAndOrderBy">条件</param> protected override void BindLVData(int selNum = 0, string sqlWhereAndOrderBy = null) { this.lvContent.BeginUpdate(); this.lvContent.Items.Clear(); try { if (selNum <= 0) { selNum = this.DefaultPageSize; } if (string.IsNullOrEmpty(sqlWhereAndOrderBy) || sqlWhereAndOrderBy.Equals("")) { sqlWhereAndOrderBy = "1=1"; } this.CurrentSqlWhere = sqlWhereAndOrderBy; IList <CardLog> listData = null; IDAL.ICardLog objDAL = DALFactory.DALFactory.CardLog(); listData = objDAL.GetListByWhere(selNum, sqlWhereAndOrderBy); if (!(listData == null || listData.Count <= 0)) { foreach (CardLog model in listData) { //序号,50|刷卡时间,130|卡号,80|卡片类型,70|有效期,100|设备类型,100|设备号,100|小区编码,60|楼栋编码,60|单元编码,60|房间编码,80|卡片系列号,210|持卡者姓名,100|联系电话,100|所在房间,100|所在单元,100|所在楼栋,100|所在小区,120 ListViewItem item = new ListViewItem(new string[] { Convert.ToString(lvContent.Items.Count + 1), Functions.ConvertToNormalTime(model.CreateDate).ToString(Config.LongTimeFormat), model.CardNo.ToString(), model.CardTypeDesc, ((model.CardNo <= 0 || (model.CardType < 0 || model.CardType > 2)) ? "未知" : Functions.ConvertToNormalTime(model.ExpiryDate).ToString(Config.TimeFormat)) , model.DeviceTypeDesc, model.DeviceNo, ((model.RAreaCode >= 0) ? FormatBuildingCode(model.RAreaCode) : ""), ((model.RBuildCode >= 0) ? FormatBuildingCode(model.RBuildCode) : ""), ((model.RUnitCode >= 0) ? FormatBuildingCode(model.RUnitCode) : ""), ((model.RRoomCode >= 0) ? FormatRoomCode(model.RRoomCode) : ""), model.SerialNo, model.Contact, model.Tel, model.RoomName, model.UnitName, model.BuildName, model.AreaName }) { Tag = model, Font = new Font("宋体", 9, FontStyle.Regular) }; this.lvContent.Items.Add(item); } } } catch (Exception err) { CMessageBox.ShowWaring(err.Message, Config.DialogTitle); } this.lvContent.EndUpdate(); }
/// <summary> /// 删除数据 /// </summary> /// <param name="selectedItems)">当前选择的所有项</param> protected override void OnDelete(ListView.SelectedListViewItemCollection selectedItems) { if (MessageBox.Show("确定要删除当前选择的用户吗?", Config.DialogTitle, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) { return; } int iSuccNum = 0; int iFaultNum = 0; foreach (ListViewItem selectedItem in selectedItems) { UserInfo objModel = (UserInfo)selectedItem.Tag; IDAL.IUserInfo objDal = DALFactory.DALFactory.UserInfo(); if (objDal.Delete(objModel.ID)) { iSuccNum++; } else { iFaultNum++; } } if (iSuccNum > 0) { //重新刷新列表 BindLVData(0, this.CurrentSqlWhere); } if (iSuccNum == 0) { CMessageBox.ShowError("对不起,删除失败!", Config.DialogTitle); } else if (iFaultNum == 0) { CMessageBox.ShowSucc("恭喜您,删除成功!", Config.DialogTitle); } else { CMessageBox.ShowSucc(string.Format("{0}个删除成功,{1}个删除失败", iSuccNum, iFaultNum), Config.DialogTitle); } }
void miT4Project_Click(object sender, EventArgs e) { if (Project == null) { CMessageBox.Show(this, "没有项目文件,请新建或者载入"); return; } if (_uiT4Setting == null || _uiT4Setting.IsDisposed) { _uiT4Setting = new T4SettingFrm(this); } ToolStripMenuItem xsender = sender as ToolStripMenuItem; _uiT4Setting.Tag = Project; _uiT4Setting.CodeMode = CodeModes.Project; _uiT4Setting.TTFile = xsender.Tag.ToString(); //_uiT4Setting.LoadSettings(); //Navigate(_uiT4Setting); _uiT4Setting.Show(); }
private void SaveOneFile(CFile file) { saveDialog.Filter = $"(*.{file.Extension.ToString().ToLower()})|*.{file.Extension.ToString().ToLower()}"; saveDialog.Title = "Download File"; saveDialog.FileName = file.FileName; if (saveDialog.ShowDialog() == DialogResult.OK) { try { File.WriteAllBytes(saveDialog.FileName, file.Contents); StatusUpdate?.Invoke(this, new StatusArgs(file.FullFileName + " downloaded from Job# " + JobHandler.Instance.CurrentJob.JobNumber + ". Saved to " + saveDialog.FileName)); } catch (Exception) { CMessageBox.Show("There was an error saving the file: " + saveDialog.FileName + "\nPlease try again.", "Error", MessageBoxButtons.OK, Resources.error_64x64); StatusUpdate?.Invoke(this, new StatusArgs("File " + file.FullFileName + " could not be saved.")); } } }
private void SetData() { if (result < 0) { FrameworkTools.ErrorProcessing.WriteLog(new Exception("")); CMessageBox.Show(this.ParentMainControl, Resources.Error_on_bitmap_create, Resources.Warning); } else { setTemperature(); pbxThermalmager.Image = (colorMode == ColorMode.GRAYSCALE) ? getBitmapGrayscale() : getBitmapColor(); if (firstMeasurementProgress) { timer.Enabled = true; firstMeasurementProgress = false; measurementProgress = true; } } }
void BuildT4Project(object sender, EventArgs e) { if (Project == null) { CMessageBox.Show(this, "没有项目文件,请新建或者载入"); return; } if (t4SettingFrm == null || t4SettingFrm.IsDisposed) { t4SettingFrm = new T4SettingFrm(this); } ToolStripMenuItem xsender = sender as ToolStripMenuItem; t4SettingFrm.Tag = Project; t4SettingFrm.CodeMode = CodeModes.Project; t4SettingFrm.TTFile = xsender.Tag.ToString(); //t4SettingFrm.LoadSettings(); //Navigate(t4SettingFrm); t4SettingFrm.Show(); }
public void SaveProject() { //_Project = treeProject.Tag as Project; if (Project == null) { //MessageBox.Show("", "错误"); CMessageBox.Show(this, "没有项目文件,请新建或者载入"); return; } if (string.IsNullOrEmpty(projectPath)) { Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog(); dlg.FileName = Project.Namespace + ".xml"; dlg.Filter = "Xml文件|*.xml"; Nullable <bool> result = dlg.ShowDialog(); if (result == true) { projectPath = dlg.FileName; } else { return; } } try { Project.SaveProject(projectPath); _treeFrm._Modified = false; Helpler.ChangeTitle(true, _treeFrm); _treeFrm.projectPath = projectPath; CMessageBox.Show(this, "项目保存成功"); } catch (Exception ex) { CMessageBox.Show(this, "文件保存失败:\r\n\r\n\t" + ex.Message); } }
private void BtnCheckDBSetting_Click(object sender, EventArgs e) { DBSetting objDBSetting = GetSettingFromUI(); if (!CheckDBSettings(objDBSetting, out string strErrInfo)) { CMessageBox.ShowError(string.Format("数据库配置错误,错误如下:\r\n{0}", strErrInfo), Config.DialogTitle); return; } DBLinkTestForm objModal = new DBLinkTestForm(string.Format("SERVER={0};Port={1};User ID={2};Password={3};Charset={4};Database={5};allow user variables=true", objDBSetting.DB_IP, "3308", objDBSetting.DB_User, objDBSetting.DB_Password, System.Text.Encoding.Default.HeaderName.ToString(), objDBSetting.DB_Name)); if (objModal.ShowDialog() == DialogResult.OK) { CMessageBox.ShowSucc(string.Format("恭喜您,数据库连接成功!"), Config.DialogTitle); } else if (objModal.ShowDialog() == DialogResult.No) { CMessageBox.ShowError(string.Format("对不起,数据库连接失败!请重新配置软件参数!"), Config.DialogTitle); File.Delete(RunVariable.IniPathAndFileName); } }
private void btnSave_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(Col.Name)) { CMessageBox.Show(_Owner, "列名不能为空", "错误提示"); return; } //try //{ _treeFrm.UpdateColNode(Col); _treeFrm.WriteSqlLog(_Col, oldColName); //} //catch (Exception ex) //{ // CMessageBox.Show(_Owner, ex.Message, "发生错误", , MessageBoxButtons.OK,MessageBoxIcon.Error); // return; // } this.Close(); //this.Visible = false; //_treeFrm.Operation = ChangeTypes.None; }
private void Edit_Click(object sender, EventArgs e) { if (!this.CurrentUserInfo.Flag.Equals(0)) { return; } if (this.lvContent.FocusedItem == null) { CMessageBox.ShowWaring("请选择您要修改的信息!", Config.DialogTitle); return; } if (this.lvContent.SelectedItems.Count > 1) { CMessageBox.ShowWaring("请选择一个您要修改的信息!", Config.DialogTitle); return; } if (this.IfFormLoadOk) { OnEdit(this.lvContent.FocusedItem); } }
private void btnRemoveTime_Click(object sender, EventArgs e) { DateTime selected = DateTime.Parse((string)lbTimeEntries.SelectedItem); DialogResult result = CMessageBox.Show($"Are you sure you want to remove {selected.Date.ToShortDateString()} from this job? " + $"This will remove ALL time entries associated with {selected.Date.ToShortDateString()} from this job and cannot be reversed!", "Confirm", MessageBoxButtons.YesNo, Resources.warning_64x64); if (result == DialogResult.No || result == DialogResult.Cancel) { return; } billingItems.Remove(selected.ToShortDateString()); lbTimeEntries.Items.Remove(selected.ToShortDateString()); lbTimeEntries.SelectedIndex = lbTimeEntries.Items.Count - 1; selectedListBoxIndex = lbTimeEntries.SelectedIndex; LoadData(); JobHandler.Instance.UpdateSavePending(true); }
private void InstallLicenses_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { if (e.Error != null) { CMessageBox.Show(e.Error.Message, CMessageBoxImage.Error); } else if (e.Result != null) { } else { } try //删除多余文件,避免出错 { DirectoryInfo di = new DirectoryInfo(a + "licenses\\"); di.Delete(true); } catch { } InstallLicenses.Dispose(); }
private void OpenForm(CardManage.Model.Menu objMenuInfo) { if (objMenuInfo == null || string.IsNullOrEmpty(objMenuInfo.FormName)) { return; } try { FormBase objForm; string strFormName = string.Format("{0}Form", objMenuInfo.Name); objForm = GetFormByFormName(strFormName); if (objForm != null) { if (objForm.WindowState == FormWindowState.Minimized || objForm.WindowState == FormWindowState.Normal) { objForm.WindowState = FormWindowState.Maximized; } objForm.Activate(); } else { objForm = (FormBase)Activator.CreateInstance(Type.GetType(string.Format("CardManage.Forms.{0}", objMenuInfo.FormName)), new object[] { objMenuInfo.Title, objMenuInfo.IsModal, RunVariable.CurrentUserInfo, objMenuInfo.WindowSize, objMenuInfo.Flag }); objForm.Name = strFormName; if (objMenuInfo.IsModal) { objForm.ShowDialog(); } else { objForm.MdiParent = this._MainForm; objForm.Show(); } } } catch (Exception err) { CMessageBox.ShowError(string.Format("出现异常,异常信息如下:{0}", err.Message), Config.DialogTitle); } }
private void BackgroundDoWork(string FileName, string Arguments) { try { Process p = new Process(); p.StartInfo.FileName = FileName; if (Arguments != null) { if (FileName == string.Empty) { p.StartInfo.FileName = "cscript"; if (File.Exists("files\\activate\\ospp_" + Find("Culture") + ".vbs")) { p.StartInfo.Arguments = "//Nologo files\\activate\\ospp_" + Find("Culture") + ".vbs /" + Arguments; } else { p.StartInfo.Arguments = "//Nologo files\\activate\\ospp.vbs /" + Arguments; } } else { p.StartInfo.Arguments = Arguments; } } p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardInput = true; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.CreateNoWindow = true; p.EnableRaisingEvents = true; p.OutputDataReceived += new DataReceivedEventHandler(Process_OutputDataReceived); p.Exited += Process_Exited; p.Start(); p.BeginOutputReadLine(); } catch (Exception ex) { CMessageBox.Show(ex.Message, CMessageBoxImage.Error); } }
/// <summary> /// 创建全部数据 /// </summary> private void DeleteAllData(object state) { bool bIfSucc = false; string strErrMessag = "未知错误"; SetButtonEnabled(false); try { if (this._FormIfClose) { return; } IDAL.ISys objDal = DALFactory.DALFactory.Sys(); bIfSucc = objDal.DeleteData(0); if (bIfSucc) { InitTree(); } } catch (Exception err) { strErrMessag = err.Message; } if (bIfSucc) { RefreshTreeByThread(); } //SetButtonEnabled(true); if (bIfSucc) { CMessageBox.ShowSucc("恭喜您,删除成功!", Config.DialogTitle); //当建筑信息删除时,通知其他已开启的树 //Manager.GetInstance().BuildingDataChangeNotice(); } else { CMessageBox.ShowError(string.Format("对不起,删除失败,错误原因:\r\n{0}", strErrMessag), Config.DialogTitle); } }
private void treeFrm_FormClosing(object sender, FormClosingEventArgs e) { if (Text.Contains("*")) { DialogResult dlg = CMessageBox.Show(this, "数据结构已经改变,是否保存?", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question); if (dlg == DialogResult.OK) { if (!_Owner.SaveProject()) { e.Cancel = true; return; } } else { e.Cancel = true; return; } } _Owner.Project = null; _Owner.RecordHistory(); }
/// <summary> /// 回调方法-配置器当写卡返回时 /// </summary> private void CardViewForm_OnWriteCardReponse(uint iCardNo, string strErrInfo) { if (this._LastCard == null) { return; } if (iCardNo != uint.MaxValue && string.IsNullOrEmpty(strErrInfo)) { try { this.Invoke(new EventHandler(delegate { txtCardNo.Text = iCardNo.ToString(); this._LastCard.CardNo = iCardNo; //保存数据库 IDAL.ICard objDAL = DALFactory.DALFactory.Card(); if (!_UpdateFlag) { int iNewID = objDAL.Add(this._LastCard, out string strErrorInfo); if (iNewID <= 0) { CMessageBox.ShowError(string.Format("恭喜您,写卡成功,但是保存卡片数据到数据库失败,错误如下:\r\n{0}!", strErrorInfo), Config.DialogTitle); return; } } else { bool bIfSucc = objDAL.Update(this._LastCard, out string strErrorInfo); if (!bIfSucc) { CMessageBox.ShowError(string.Format("恭喜您,写卡成功,但是保存卡片数据到数据库失败,错误如下:\r\n{0}!", strErrorInfo), Config.DialogTitle); return; } } Manager.GetInstance().CardDataChangeNotice(); CMessageBox.ShowSucc(string.Format("恭喜您,写卡和保存卡片数据到数据库都成功!"), Config.DialogTitle); })); }
protected Boolean verifyData() { if (!validateData()) { return(false); } CUtil.EnableForm(false, this); CTable newobj = OnixWebServiceAPI.SubmitObjectAPI(verifyAPIName, vw.GetDbObject()); CUtil.EnableForm(true, this); if (newobj == null) { //Error here CHelper.ShowErorMessage(OnixWebServiceAPI.GetLastErrorDescription(), "ERROR_USER_ADD", null); return(false); } MInventoryDoc vcd = new MInventoryDoc(newobj); vcd.InitErrorItem(); if (vcd.ErrorItems.Count > 0) { WinErrorDetails w = new WinErrorDetails(vcd.ErrorItems, "InventoryDoc"); w.Title = CLanguage.getValue("approve_error"); w.ShowDialog(); return(false); } else { String msg = CLanguage.getValue("VERIFY_SUCCESS"); CMessageBox.Show(msg, "SUCCESS", MessageBoxButton.OK, MessageBoxImage.Information); } return(true); }
/// <summary> /// 检查序列化文件是否存在,如果存在就读取再保存到access数据库,不存在就new一个新的list /// </summary> private void CheckFileBuff() { try { //检查目录下是否有序列化文件,若存在就反序列化读取,不存在就创new一个新的list if (File.Exists(fileName)) { DataBase.DBHelp.FileName = DataBase.DBHelp.fileName; //指定数据库路径 BinaryFile.FileName = fileName; //指定序列化文件路径 //读取出序列化文件的内容到List表 recLst = BinaryFile.ReadBinary().ConvertAll(s => (Models.DataBaseRecord)s); //读取序列化文件内容到list Models.DataBaseRecord rec = recLst[0]; //获取出列表第一个参数项 List <string> listTem = new List <string>(); //实例化一个类属性让下面SQL语读出查找的项用来做判断 listTem = DataBase.CQServices.GetRecordSql(@"SELECT DataSheet.serialNumber FROM DataSheet WHERE(((DataSheet.serialNumber) = '" + rec.serialNumber + @"'))"); //判断数据库里有无重复编号,有的话就删除,没有就插入 if (listTem.Count > 0) { DataBase.CQServices.DeleteRecord(rec.serialNumber); //删除重复项 } DataBase.CQServices.BulckInsert(recLst); //向ACCESS数据库添加数据列表 File.Delete(fileName); //删除序列化文件 recLst.Clear(); //清空数据列表 } else { recLst.Clear(); } } catch (Exception ex) { CMessageBox.Show(ex.Message, "提示"); return; } }
protected override void BtnOK_Click(object sender, EventArgs e) { List <Model.NodeData> listSelectedData = new List <Model.NodeData>(); GetSelectedNodes(ref listSelectedData, this.tv.Nodes[0]); if (listSelectedData.Count > 0) { if (MessageBox.Show("删除后,数据将无法恢复,您确定要删除您勾选的那些数据吗?", Config.DialogTitle, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) { return; } Model.SelecedTreeNodeData objSelecedTreeNodeData = new Model.SelecedTreeNodeData() { SelectedDataList = listSelectedData }; SetButtonEnabled(false); ThreadPool.QueueUserWorkItem(new WaitCallback(DeleteSelectedData), objSelecedTreeNodeData); } else { CMessageBox.ShowWaring("请勾选您要删除的数据!", Config.DialogTitle); } }
public void NodeUp() { try { TreeNode myParent = _CurrentTreeViewItem.Parent as TreeNode; int index = 0; for (; index < myParent.Nodes.Count; index++) { if (_CurrentTreeViewItem == myParent.Nodes[index]) { break; } } myParent.Nodes.Remove(_CurrentTreeViewItem); myParent.Nodes.Insert(index - 1 >= 0 ? index - 1 : 0, _CurrentTreeViewItem); if (myParent.Tag is Project) //表移动 { _Project.Tables.Remove(_CurrentTreeViewItem.Tag as Table); _Project.Tables.Insert(index - 1 >= 0 ? index - 1 : 0, _CurrentTreeViewItem.Tag as Table); } else { Table table = myParent.Tag as Table; table.Cols.Remove(_CurrentTreeViewItem.Tag as Col); table.Cols.Insert(index - 1 >= 0 ? index - 1 : 0, _CurrentTreeViewItem.Tag as Col); } //_CurrentTreeViewItem.IsSelected = true; //ShowInfo("上移成功。"); } catch { CMessageBox.Show(_Owner, "哥,不能再移动了,放过我吧", "提示"); } }
public void SaveSettings() { //Log file options Settings.Default.OverwriteLogFile = radOverwriteLog.Checked; if (!lblPath.Text.Equals("<PATH>")) { Settings.Default.LogFilePath = lblPath.Text; } Settings.Default.LogAutoSaveInterval = (int)nudAutoSaveInterval.Value; //Set the new autosave intervals RuntimeVars.Instance.MainForm.SetLogAutosaveInterval(Settings.Default.LogAutoSaveInterval); //Other file options if (!lblReportPath.Text.Equals("<PATH>")) { Settings.Default.DefaultSavePath = lblReportPath.Text; } Settings.Default.Save(); CMessageBox.Show("An application restart is needed for some logging settings to take full effect. Please save your work and restart the application.", "Restart Required", MessageBoxButtons.OK, Resources.warning_64x64); }
private void LoadDatabase(object sender, EventArgs e) { if (combbDatabase.Items.Count > 0) return; //combbDatabase.Items.Clear(); string conStr1 = "Persist Security Info=False;User ID={1};Password={2};Server={0};Initial Catalog=master"; string conStr2 = "Persist Security Info=False;Integrated Security=true;Server={0};Initial Catalog=master"; string conStr = ""; if (string.IsNullOrEmpty(tbxUserName.Text.Trim())) { conStr = string.Format(conStr2, tbxServer.Text); } else { conStr = string.Format(conStr1, tbxServer.Text, tbxUserName.Text, tbxPassword.Text); } SqlConnection con = new SqlConnection(conStr); try { con.Open(); } catch (Exception ex) { CMessageBox.Show(_Owner, ex.Message, "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } SqlCommand cmd = new SqlCommand("select name from sysdatabases", con); IDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { combbDatabase.Items.Add(reader.GetString(0)); } reader.Close(); con.Close(); }
private void TsbSaveDebugContent_Click(object sender, EventArgs e) { SaveFileDialog saveFileDialog1 = new SaveFileDialog() { Filter = " txt files(*.txt)|*.txt", //设置文件类型 RestoreDirectory = true //保存对话框是否记忆上次打开的目录 }; if (saveFileDialog1.ShowDialog() == DialogResult.OK) { try { StreamWriter aWriter = new StreamWriter(saveFileDialog1.OpenFile()); aWriter.Write(Regex.Replace(this.tbxComunicateData.Text, "\n", "\r\n", RegexOptions.IgnoreCase)); aWriter.Close(); aWriter = null; CMessageBox.ShowSucc("保存文件成功!", Config.DialogTitle); } catch (Exception err) { CMessageBox.ShowError(string.Format("保存文件失败,错误原因:{0}", err), Config.DialogTitle); } } }
private void btnOpen_Click(object sender, EventArgs e) { try { int iPort; for (iPort = 1001; iPort <= 1016; iPort++) { iRetUSB = CVRSDK.CVR_InitComm(iPort); if (iRetUSB == 1) { Console.WriteLine("USB打开:" + iPort); break; } } if (iRetUSB != 1) { for (iPort = 1; iPort <= 4; iPort++) { iRetCOM = CVRSDK.CVR_InitComm(iPort); if (iRetCOM == 1) { break; } } } if (iRetUSB == 1 || iRetCOM == 1) { timerID.Interval = 500; timerID.Start(); } } catch (Exception ex) { CMessageBox.Show(ex.ToString()); } }
public void ExportToExcel(DateTime dt, string stationName) { // 弹出对话框,并导出到Excel文件 int year = dt.Year; int month = dt.Month; string name = stationName + "_" + year + "年" + month + "月"; SaveFileDialog dlg = new SaveFileDialog(); dlg.FileName = name + "水位表"; dlg.Filter = "Excel文件(*.xls)|*.xls|所有文件(*.*)|*.*"; PrintDocument pd = new PrintDocument(); if (DialogResult.OK == dlg.ShowDialog()) { // 保存到Excel表格中 System.Data.DataTable dataTable = new System.Data.DataTable(); for (int i = 1; i < 25; i++) { dataTable.Columns.Add(i.ToString() + "时"); } dataTable.Columns.Add(aver); dataTable.Columns.Add(max); dataTable.Columns.Add(maxTime); dataTable.Columns.Add(min); dataTable.Columns.Add(minTime); // 逐行读取数据 int iRowCount = m_dataTable.Rows.Count; DataRow row0 = dataTable.NewRow(); for (int i = 0; i < iRowCount; ++i) { // 赋值到dataTable中去 DataRow row = dataTable.NewRow(); // 多余的一列是state for (int j = 0; j < m_dataTable.Columns.Count - 1; ++j) { row[j] = m_dataTable.Rows[i][j]; } dataTable.Rows.Add(row); } // 显示提示框 CMessageBox box = new CMessageBox() { MessageInfo = "正在导出表格,请稍候" }; box.ShowDialog(this); if (CExcelExport.ExportToExcelWrapper(dataTable, dlg.FileName, name + "水位表")) { //box.Invoke((Action)delegate { box.Close(); }); box.CloseDialog(); MessageBox.Show(string.Format("导出成功,保存在文件\"{0}\"中", dlg.FileName)); } else { //box.Invoke((Action)delegate { box.Close(); }); box.CloseDialog(); MessageBox.Show("导出失败"); } }//end of if dialog okay }
public void ExportToExcelNew(DataGridView dgv, DateTime dt, string stationName) { int year = dt.Year; int month = dt.Month; string name = stationName + "_" + year + "年" + month + "月"; SaveFileDialog dlg = new SaveFileDialog(); dlg.FileName = name + "水位表"; dlg.Filter = "Excel文件(*.xlsx)|*.xlsx|Excel文件(*.xls)|*.xls|所有文件(*.*)|*.*"; if (DialogResult.OK == dlg.ShowDialog()) { int rowscount = dgv.Rows.Count; int colscount = dgv.Columns.Count; //行数必须大于0 if (rowscount <= 0) { MessageBox.Show("没有数据可供保存 ", "提示 ", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } //列数必须大于0 if (colscount <= 0) { MessageBox.Show("没有数据可供保存 ", "提示 ", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } //行数不可以大于65536 if (rowscount > 65536) { MessageBox.Show("数据记录数太多(最多不能超过65536条),不能保存 ", "提示 ", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } FileInfo file = new FileInfo(dlg.FileName); if (file.Exists) { try { file.Delete(); } catch (Exception error) { MessageBox.Show(error.Message, "删除失败 ", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } } CMessageBox box = new CMessageBox(); box.MessageInfo = "正在导出报表"; box.ShowDialog(this); this.Enabled = false; Microsoft.Office.Interop.Excel.Application objExcel = null; Microsoft.Office.Interop.Excel.Workbook objWorkbook = null; Microsoft.Office.Interop.Excel.Worksheet objsheet = null; ProgressBar tempProgressBar = new ProgressBar(); try { //申明对象 objExcel = new Microsoft.Office.Interop.Excel.Application(); objWorkbook = objExcel.Workbooks.Add(Missing.Value); objsheet = (Microsoft.Office.Interop.Excel.Worksheet)objWorkbook.ActiveSheet; //设置EXCEL不可见 objExcel.Visible = false; objsheet.DisplayAutomaticPageBreaks = true; //显示分页线 objsheet.PageSetup.CenterFooter = "第 &P 页,共 &N 页"; objsheet.PageSetup.CenterHorizontally = true; //水平居中 objsheet.PageSetup.PrintTitleRows = "$1:$1"; //顶端标题行 objsheet.PageSetup.PaperSize = Microsoft.Office.Interop.Excel.XlPaperSize.xlPaperA4; //A4纸张大小 objsheet.PageSetup.Orientation = Microsoft.Office.Interop.Excel.XlPageOrientation.xlLandscape; //纸张方向.纵向 Range range2 = objsheet.Range[objsheet.Cells[1, 1], objsheet.Cells[1, 8]]; Range range = objsheet.Range[objsheet.Cells[1, 9], objsheet.Cells[1, 30]]; range.Font.Bold = true; range.Font.ColorIndex = 0; range2.Font.Bold = true; range2.Font.ColorIndex = 0; objsheet.Cells[1, 7] = name + "水位表"; int displayColumnsCount = 1; objsheet.Cells[2, displayColumnsCount] = "日/时"; displayColumnsCount++; for (int i = 1; i <= 24; i++) { if (dgv.Columns[i].Visible == true) { objsheet.Cells[2, displayColumnsCount] = " " + (i + "时").ToString().Trim(); displayColumnsCount++; } } objsheet.Cells[2, displayColumnsCount] = " 平均"; displayColumnsCount++; objsheet.Cells[2, displayColumnsCount] = " 最大"; displayColumnsCount++; objsheet.Cells[2, displayColumnsCount] = " 最大时分"; displayColumnsCount++; objsheet.Cells[2, displayColumnsCount] = " 最小"; displayColumnsCount++; objsheet.Cells[2, displayColumnsCount] = " 最小时分"; displayColumnsCount++; for (int row = 0; row <= dgv.RowCount; row++) { //tempProgressBar.PerformStep(); displayColumnsCount = 1; for (int col = 0; col < colscount; col++) { if (dgv.Columns[col].Visible == true) { try { objsheet.Cells[row + 3, displayColumnsCount] = dgv.Rows[row].Cells[col].Value.ToString().Trim(); displayColumnsCount++; } catch (Exception) { } } } } objWorkbook.SaveAs(dlg.FileName, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlShared, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value); } catch (Exception error) { MessageBox.Show(error.Message, "警告 ", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } finally { //关闭Excel应用 if (objWorkbook != null) { objWorkbook.Close(Missing.Value, Missing.Value, Missing.Value); } if (objExcel.Workbooks != null) { objExcel.Workbooks.Close(); } if (objExcel != null) { objExcel.Quit(); } objsheet = null; objWorkbook = null; objExcel = null; } this.Enabled = true; box.CloseDialog(); MessageBox.Show(dlg.FileName + "导出完毕! ", "提示 ", MessageBoxButtons.OK, MessageBoxIcon.Information); } }
public void ExportToExcelNew(DataGridView dgv, DateTime dt, string stationName) { int year = dt.Year; int month = dt.Month; string name = stationName + "_" + year + "年"; SaveFileDialog dlg = new SaveFileDialog(); dlg.FileName = name + "水位表"; dlg.Filter = "Excel文件(*.xls)|*.xls|所有文件(*.*)|*.*"; if (DialogResult.OK == dlg.ShowDialog()) { int rowscount = dgv.Rows.Count; int colscount = dgv.Columns.Count; if (rowscount <= 0) { MessageBox.Show("没有数据可供保存 ", "提示 ", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } if (colscount <= 0) { MessageBox.Show("没有数据可供保存 ", "提示 ", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } if (rowscount > 65536) { MessageBox.Show("数据记录数太多(最多不能超过65536条),不能保存 ", "提示 ", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } if (colscount > 255) { MessageBox.Show("数据记录行数太多,不能保存 ", "提示 ", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } FileInfo file = new FileInfo(dlg.FileName); if (file.Exists) { try { file.Delete(); } catch (Exception error) { MessageBox.Show(error.Message, "删除失败 ", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } } CMessageBox box = new CMessageBox(); box.MessageInfo = "正在导出报表"; box.ShowDialog(this); this.Enabled = false; Microsoft.Office.Interop.Excel.Application objExcel = null; Microsoft.Office.Interop.Excel.Workbook objWorkbook = null; Microsoft.Office.Interop.Excel.Worksheet objsheet = null; try { //申明对象 objExcel = new Microsoft.Office.Interop.Excel.Application(); objWorkbook = objExcel.Workbooks.Add(Missing.Value); objsheet = (Microsoft.Office.Interop.Excel.Worksheet)objWorkbook.ActiveSheet; //设置EXCEL不可见 objExcel.Visible = false; objsheet.PageSetup.PaperSize = Microsoft.Office.Interop.Excel.XlPaperSize.xlPaperA4; //A4纸张大小 objsheet.PageSetup.Orientation = Microsoft.Office.Interop.Excel.XlPageOrientation.xlLandscape; //纸张方向.纵向 Range range2 = objsheet.Range[objsheet.Cells[1, 1], objsheet.Cells[1, 8]]; Range range = objsheet.Range[objsheet.Cells[1, 9], objsheet.Cells[1, 26]]; range.Font.Bold = true; // range.Font. //设置字体颜色 range.Font.ColorIndex = 0; //设置颜色背景 range.Interior.ColorIndex = 15; range2.Font.Bold = true; // range.Font. //设置字体颜色 range2.Font.ColorIndex = 0; //设置颜色背景 range2.Interior.ColorIndex = 15; objsheet.Cells[1, 7] = name + "水位表"; // ((Microsoft.Office.Interop.Excel.Range)objsheet.Cells[1, 1]).HorizontalAlignment = Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter; //向Excel中写入表格的表头 int displayColumnsCount = 1; objsheet.Cells[2, displayColumnsCount] = "站点/日期"; displayColumnsCount++; for (int i = 1; i <= 31; i++) { if (dgv.Columns[i].Visible == true) { objsheet.Cells[2, displayColumnsCount] = " " + i + "日"; displayColumnsCount++; } } //objsheet.Cells[2, displayColumnsCount] = "日雨量"; //设置进度条 //tempProgressBar.Refresh(); //tempProgressBar.Visible = true; //tempProgressBar.Minimum=1; //tempProgressBar.Maximum=dgv.RowCount; //tempProgressBar.Step=1; //向Excel中逐行逐列写入表格中的数据 for (int row = 0; row <= dgv.RowCount; row++) { //tempProgressBar.PerformStep(); displayColumnsCount = 1; for (int col = 0; col < colscount; col++) { if (dgv.Columns[col].Visible == true) { try { objsheet.Cells[row + 3, displayColumnsCount] = "'" + dgv.Rows[row].Cells[col].Value.ToString().Trim(); displayColumnsCount++; } catch (Exception) { } } } } //隐藏进度条 //tempProgressBar.Visible = false; //保存文件 objWorkbook.SaveAs(dlg.FileName, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlShared, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value); } catch (Exception error) { MessageBox.Show(error.Message, "警告 ", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } finally { //关闭Excel应用 if (objWorkbook != null) { objWorkbook.Close(Missing.Value, Missing.Value, Missing.Value); } if (objExcel.Workbooks != null) { objExcel.Workbooks.Close(); } if (objExcel != null) { objExcel.Quit(); } objsheet = null; objWorkbook = null; objExcel = null; } this.Enabled = true; box.CloseDialog(); MessageBox.Show(dlg.FileName + "/n/n导出完毕! ", "提示 ", MessageBoxButtons.OK, MessageBoxIcon.Information); } }