@Aiti
2018-05-28T01:19:06.000000Z
字数 35914
阅读 801
未分类
protected void gvAll_CellEditorInitialize(object sender, ASPxGridViewEditorEventArgs e)
参数sender:指当前控件;
(sender as ASPxGridView);(sender as ASPxComboBox);等等!
参数e:当前行值;
<dx:GridViewDataColumn FieldName="Content" VisibleIndex="6" ><EditFormSettings Visible="True" ColumnSpan="2" /><EditItemTemplate><dx:ASPxHtmlEditor ID="html" runat="server" Html='<%# Bind("Content") %>'><Settings AllowHtmlView="false" /><SettingsDialogs><InsertImageDialog><SettingsImageUpload UploadFolder="StandardsInfo/UploadFiles/Images/"><ValidationSettings AllowedFileExtensions=".jpe,.jpeg,.jpg,.gif,.png,.webp" MaxFileSize="500000"></ValidationSettings></SettingsImageUpload></InsertImageDialog></SettingsDialogs></dx:ASPxHtmlEditor></EditItemTemplate></dx:GridViewDataColumn>
//控件直接做成多选框
<div class="search-name">项目状态:</div><dx:ASPxCheckBoxList runat="server" ID="chxPStatus" CssClass="inb" RepeatDirection="Horizontal" ClientIDMode="Static"></dx:ASPxCheckBoxList><dx:ASPxCheckBox runat="server" ID="AllPStatus" ClientIDMode="Static" Text="全部" CssClass="inb" Checked="true"><ClientSideEvents CheckedChanged="AllPStatusChange" /></dx:ASPxCheckBox></div>if (!IsPostBack){EnumHelper.SetListControl(chxPStatus, typeof(ProjectStatus));chxPStatus.Items[0].Selected = chxPStatus.Items[1].Selected = true;}
//控件里面套控件直接做成多选框
<dx:GridViewDataColumn FieldName="Properties" Caption="属性" VisibleIndex="4"><EditItemTemplate><dx:ASPxCheckBoxList runat="server" ID="chxProperties" ></dx:ASPxCheckBoxList></EditItemTemplate></dx:GridViewDataColumn>protected void gvAll_HtmlDataCellPrepared(object sender, ASPxGridViewTableDataCellEventArgs e){if (gvAll.EditingRowVisibleIndex == e.VisibleIndex && !gvAll.IsNewRowEditing)if (e.DataColumn.FieldName == "Properties"){var cbl = gvAll.FindEditRowCellTemplateControl(gvAll.DataColumns["Properties"], "chxProperties") as ASPxCheckBoxList;if (cbl != null)EnumHelper.SetListControl(cbl, typeof(ArticleProperty));}}
这只是显示出来;然后再绑定数据;新建,编辑,保存更新时都要重新保存数据
修改事件
1.首先增加上传数据到数据库的事件
protected void gvAll_RowInserting(object sender, DevExpress.Web.Data.ASPxDataInsertingEventArgs e){e.NewValues["Properties"] = GetProperties();}
2.添加更新数据的事件
protected void gvAll_RowUpdating(object sender, DevExpress.Web.Data.ASPxDataUpdatingEventArgs e){e.NewValues["Properties"] = GetProperties();}
3.把相同的代码块做成一个返回函数;获取选择的多选框
private ArticleProperty GetProperties(){var cbl = gvAll.FindEditRowCellTemplateControl(gvAll.DataColumns["Properties"], "chxProperties") as ASPxCheckBoxList;ArticleProperty appLevels = 0;foreach (ListEditItem item in cbl.SelectedItems){appLevels += int.Parse(item.Value.ToString());}return appLevels;}
4.这时候会发现“新建”时;多选框不显示;编辑更新保存数据时不成功;主要原因是:新建时,gvAll_HtmlDataCellPrepared事件中判断条件使得CheckBoxList没有初始化;所以多选框不显示;编辑更新数据不成功是因为每次进入返回函数时,之前都进入了gvAll_HtmlDataCellPrepared函数会进入if里面,多选框会被初始化;所以前端选择的都被初始化了。
- 解决方法:
建立CheckBoxList自己的事件初始化多选框;
//前端代码<dx:GridViewDataColumn FieldName="Properties" Caption="属性" VisibleIndex="11"><EditItemTemplate><dx:ASPxCheckBoxList runat="server" ID="chxProperties" RepeatLayout="UnorderedList" OnInit="chxProperties_Init"></dx:ASPxCheckBoxList></EditItemTemplate></dx:GridViewDataColumn>//后台代码protected void chxProperties_Init(object sender, EventArgs e){var cbl = sender as ASPxCheckBoxList;// gvAll.FindEditRowCellTemplateControl(gvAll.DataColumns["Properties"], "chxProperties") as ASPxCheckBoxList; //sender as ASPxCheckBoxList;if (cbl != null)EnumHelper.SetListControl(cbl, typeof(ArticleProperty));}
新建时不进入gvAll_HtmlDataCellPrepared函数初始化了;直接保存更新的数据;编辑时;进入gvAll_HtmlDataCellPrepared;绑定选择的多选框;所以修改gvAll_HtmlDataCellPrepared
protected void gvAll_HtmlDataCellPrepared(object sender, ASPxGridViewTableDataCellEventArgs e){if ((gvAll.EditingRowVisibleIndex == e.VisibleIndex && e.DataColumn.FieldName == "Properties") && !gvAll.IsNewRowEditing){var cbl = gvAll.FindEditRowCellTemplateControl(gvAll.DataColumns["Properties"], "chxProperties") as ASPxCheckBoxList;var o = gvAll.GetRow(e.VisibleIndex) as Article;for (int i = 0; i < cbl.Items.Count; i++){if (o.Properties.HasFlag((ArticleProperty)int.Parse(cbl.Items[i].Value.ToString())))cbl.Items[i].Selected = true;}}}
- 重点
看实体类
[DisplayName("属性")]public string Properties;
看枚举类
//[Flags]public enum ArticleProperty{[Description("热门")]Hot = 0x1,[Description("推荐")]Recommoned = 0x2,[Description("通知")]Notice = 0x4,[Description("图片")]Picture = 0x8,[Description("介绍信息")]Intro = 0x16}
使用的是16进制表示的变量;当选择变量加起来超过16的话,保存过后再编辑就显示的不再是之前选择的;或者显示数字;
- 再次修改
先修改类
[NonPersistent]public string PropertieNames{get{//1,3,5var st = "";var values = Properties?.Split(',');if (values != null && values[0].Length > 0){var Leg = values.Length;foreach (var inte in values){st += Enum.Parse(typeof(ArticleProperty), inte);if (--Leg > 0)st += ',';}}return st;}}
枚举类
public enum ArticleProperty{热门 = 1,推荐 = 2,通知 = 3,图片 = 4,介绍信息 = 5}
再修该事件绑定的格式
protected void gvAll_HtmlDataCellPrepared(object sender, ASPxGridViewTableDataCellEventArgs e){if ((gvAll.EditingRowVisibleIndex == e.VisibleIndex && e.DataColumn.FieldName == "PropertieNames") && !gvAll.IsNewRowEditing){var cbl = gvAll.FindEditRowCellTemplateControl(gvAll.DataColumns["Properties"], "chxProperties") as ASPxCheckBoxList;var o = gvAll.GetRow(e.VisibleIndex) as Article;//for (int i = 0; i < cbl.Items.Count; i++)//{// if (o.Properties.HasFlag((ArticleProperty)int.Parse(cbl.Items[i].Value.ToString())))// cbl.Items[i].Selected = true;//}var values = o?.Properties?.Split(',');if (values != null && values[0].Length>0){foreach (ListEditItem item in cbl.Items){if (values.Contains(item.Value))item.Selected = true;}}}}protected void chxProperties_Init(object sender, EventArgs e){var cbl = sender as ASPxCheckBoxList;// gvAll.FindEditRowCellTemplateControl(gvAll.DataColumns["Properties"], "chxProperties") as ASPxCheckBoxList;if (cbl != null){//EnumHelper.SetListControl(cbl, typeof(ArticleProperty));foreach (var value in Enum.GetValues(typeof(ArticleProperty))){var type = (ArticleProperty)value;cbl.Items.Add(type.ToString(), ((int)type).ToString());}}}private string GetProperties(){var cbl = gvAll.FindEditRowCellTemplateControl(gvAll.DataColumns["Properties"], "chxProperties") as ASPxCheckBoxList;var count = cbl.SelectedItems.Count;if (count <= 0) return "";var buffer = new StringBuilder();foreach (ListEditItem item in cbl.SelectedItems){buffer.Append(item.Value);if (--count > 0)buffer.Append(',');}return buffer.ToString();}
至此完成了枚举类在GridView控件中变成多选框的问题!!!
<asp:Label runat="server" Text='<%# Eval("PropertieNames").ToString().Contains("通知")?"通知":"" %> '></asp:Label>
<script src="../assets/global/plugins/jquery.min.js" type="text/javascript"></script><script type="text/javascript">jQuery(function ($) {$(function(){$(".btn-group").each(function () {if(HF.Get($(this).data("group"))){$(this).find(".btn[data-criteria='"+HF.Get($(this).data("group"))+"']").addClass("focus");}else{$(this).find(".btn:first").addClass("focus");}});});$(".btn-group .btn").click(function(){$(".btn-group .btn").click(function () {$(this).parent().find(".btn").removeClass("focus");$(this).addClass("focus");HF.Set($(this).parent().data("group"), $(this).data("criteria"));gvAll.PerformCallback("Go-1"); //转到第一页});var type = $(this).data("criteria");switch (type) {case "Day":gvD.SetVisiable = true;gvW.SetVisiable = false;gvM.SetVisiable = false;//document.getElementById("gvD").style.display = "block";//document.getElementById("gvW").style.display = "none";//document.getElementById("gvM").style.display = "none";break;case "Week":gvD.SetVisiable = false;gvW.SetVisiable = true;gvM.SetVisiable = false;break;case "Month":gvD.SetVisiable = false;gvW.SetVisiable = false;gvM.SetVisiable = true;break;}});});</script>
<div class="panel panel-default blue"><dx:ASPxHiddenField ID="HF" runat="server" ClientIDMode="Static" ></dx:ASPxHiddenField><div class="panel-body"><div class="row"><span class="ml10">报告类型:</span><div class="btn-group" data-group="flow"><button type="button" class="btn btn-default" data-criteria="Day">工作日报</button><button type="button" class="btn btn-default" data-criteria="Week">工作周报</button><button type="button" class="btn btn-default" data-criteria="Month">工作月报</button></div></div></div></div><dx:ASPxGridView runat="server" ID="gvD" KeyFieldName="Oid" DataSourceID="XpoD" Caption="工作日报" ></dx:ASPxGridView><dx:ASPxGridView runat="server" ID="gvD" KeyFieldName="Oid" DataSourceID="XpoW" Caption="工作周报" ></dx:ASPxGridView><dx:ASPxGridView runat="server" ID="gvD" KeyFieldName="Oid" DataSourceID="XpoM" Caption="工作月报" ></dx:ASPxGridView>
5.如果不是改变GridView;而是像改变查询条件则:
if (!HF.Contains("flow")){HF.Set("flow", "ALL");}if (!HF.Contains("status")){HF.Set("status", "ALL");}switch (HF.Get("flow").ToString()){case "MY":op = CriteriaOperator.And(op, CriteriaOperator.Parse($"Actor='{User.Identity.Name}'"));break;case "PASS":op = CriteriaOperator.And(op, CriteriaOperator.Parse($"Oid IN ({getCurrentUserProcessedOids("ProjectApproval", true)})"));break;}
1、在GridView中两个下拉框;工作面随隧道改变而改变;所以在隧道的ComboBox中加SelectedIndexChanged属性;两个验证方式都是动态的且不为空;之所以加Init属性;是因为在编辑时;隧道名已经存在;不存在变动;所以工作面的选项不会出现;加了之后也会调用函数对工作面数据源绑定;
<dx:GridViewDataComboBoxColumn FieldName="TunnelsName!Key" Caption="隧道名称" ><PropertiesComboBox TextField="Name" ValueField="Oid" DataSourceID="XpoTunnels"><ClientSideEvents SelectedIndexChanged ="function(s,e){ Surface.PerformCallback(s.GetValue()); }" Init="function(s,e){ Surface.PerformCallback(s.GetValue()); }" /><ValidationSettings Display="Dynamic"><RequiredField IsRequired="true" /></ValidationSettings></PropertiesComboBox></dx:GridViewDataComboBoxColumn><dx:GridViewDataComboBoxColumn FieldName="SurfaceName!Key" Caption="隧道工作面" ><PropertiesComboBox TextField="Name" ValueField="Oid" DataSourceID="XpoSurface" ClientInstanceName="Surface"><ValidationSettings Display="Dynamic"><RequiredField IsRequired="true" /></ValidationSettings></PropertiesComboBox></dx:GridViewDataComboBoxColumn>
2、通过初始化编辑方法调用Surface的回调函数;对XpoSurface绑定数据源;变量v是获取当前编辑行的工作面Oid;新建时gvAll.EditingRowVisibleIndex为负值;v=null;if条件判断是新建时e.Parameter为空字符;编辑时获取的是前台传过来的当前隧道Oid;新建时,l=0;编辑时,l为Item的长度;for循环对ComboBox绑定之前已选择的值!
protected void gvAll_CellEditorInitialize(object sender, ASPxGridViewEditorEventArgs e){if (e.Column.FieldName == "SurfaceName!Key"){(e.Editor as ASPxComboBox).Callback += Surface_Callback;}}protected void Surface_Callback(object sender, CallbackEventArgsBase e){var v = (gvAll.GetRow(gvAll.EditingRowVisibleIndex) as TunnelTest)?.SurfaceName?.Oid;if (e.Parameter != "") {XpoSurface.Criteria = $"Tunnels.Oid={e.Parameter}";(sender as ASPxComboBox).DataBind();}var l = (sender as ASPxComboBox).Items.Count;for (var i = 0; i < l; i++){if ((int)(sender as ASPxComboBox).Items[i].Value == v)(sender as ASPxComboBox).Items[i].Selected = true;}}
总结:
通过隧道的ASPxComboBox的回调调用工作面的自定义函数;
即:(e.Editor as ASPxComboBox).Callback += Surface_Callback;
2.通过gvAll.EditingRowVisibleIndex获取当前行数;再通过gvAll.GetRow获取当前行数据;
3.还能通过
XpoSurface.Criteria = $"Tunnels.Oid={e.Parameter}";
(sender as ASPxComboBox).DataBind();这种方式绑定数据源!!!!!
<dx:GridViewDataComboBoxColumn FieldName="ProjectApproval!Key" Caption="依托科研工法"><PropertiesComboBox DataSourceID="XpoProject" TextField="ProjectName" ValueField="Oid"></PropertiesComboBox></dx:GridViewDataComboBoxColumn>protected void gvAll_OnCellEditorInitialize(object sender, ASPxGridViewEditorEventArgs e){if (e.Column.FieldName == "SupportProject!Key"){AddOtherItem(e.Editor);}else if (e.Column.FieldName == "ProjectApproval!Key"){AddOtherItem(e.Editor);}}private void AddOtherItem(object editor){var cb = editor as ASPxComboBox;if (cb == null) return;cb.DataBound += (s, args) =>{var item = cb.Items.Add("其他", 0);//if (cb.Value == null)// cb.SelectedItem = item;};}
控件:
<dx:GridViewDataBinaryImageColumn FieldName="Photo1" Visible="false" Caption="受理时间照片"><EditFormSettings Visible="True" /><PropertiesBinaryImage ImageHeight="100px" ImageWidth="90px"><EditingSettings Enabled="true" UploadSettings-UploadValidationSettings-MaxFileSize="5242880"/></PropertiesBinaryImage></dx:GridViewDataBinaryImageColumn>
实体类中绑定
[DisplayName("受理照片"), NonPersistent]public byte[] Photo1{set {var url = new System.Web.UI.Page();if (value != null){byte[] array = value;string path = url.Server.MapPath("~/Images/PhotoImage/" + PatentName + "-" + PatentNo + "受理" + ".jpg");FileStream fs = new FileStream(path, FileMode.Create);fs.Write(value, 0, value.Length);fs.Close();}else{try{string path = url.Server.MapPath("~/Images/PhotoImage/" + PatentName + "-" + PatentNo + "受理" + ".jpg");System.IO.File.Delete(path);}catch { }}}get {var url = new System.Web.UI.Page();try{string path = url.Server.MapPath("~/Images/PhotoImage/" + PatentName + "-" + PatentNo + "受理" + ".jpg");FileStream fs = new FileStream(path, FileMode.Open);long size = fs.Length;byte[] array = new byte[size];fs.Read(array, 0, array.Length);fs.Close();return array;}catch { return null; }}}
第一种(传递的参数在数据源实体类中)
<dx:GridViewDataTextColumn FieldName="Name" VisibleIndex="1" Caption="项目名称" ><DataItemTemplate><asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl='<%# "~/Projects/ViewAll.aspx?id="+ Eval("Oid").ToString() %>' Text='<%# Eval("Name") %>'></asp:HyperLink></DataItemTemplate></dx:GridViewDataTextColumn>
第二种(不在本实体类中;在继承或者引用的实体类中;)
<dx:GridViewDataHyperLinkColumn FieldName="Project.Oid" PropertiesHyperLinkEdit-TextField="ProjectName" Caption="项目"><EditFormSettings Visible="False" /><PropertiesHyperLinkEdit NavigateUrlFormatString="~/Projects/ViewAll.aspx?id={0}" ></PropertiesHyperLinkEdit></dx:GridViewDataHyperLinkColumn>
其中 PropertiesHyperLinkEdit-TextField="ProjectName" 就相当于
<PropertiesHyperLinkEdit TextField="ProjectName" >
<dx:ASPxGridView ID="gvAll" runat="server" AutoGenerateColumns="False" DataSourceID="XpoMoudles" KeyFieldName="Oid" Width="100%" Caption="应用模块"><Columns><dx:GridViewCommandColumn ShowEditButton="True" ShowDeleteButton="true" ShowNewButtonInHeader="True" VisibleIndex="0" Width="100px"></dx:GridViewCommandColumn><dx:GridViewDataTextColumn FieldName="Name" VisibleIndex="1"></dx:GridViewDataTextColumn><dx:GridViewDataTextColumn FieldName="Code" VisibleIndex="2"></dx:GridViewDataTextColumn><dx:GridViewDataTextColumn FieldName="LastVersion" VisibleIndex="3"></dx:GridViewDataTextColumn></Columns><Templates><DetailRow><dx:ASPxPageControl ID="ASPxPageControl1" runat="server"><TabPages><dx:TabPage Text="应用模板"><ContentCollection><dx:ContentControl runat="server"><dx:ASPxGridView ID="gvdr" ClientInstanceName="gvdr" runat="server" AutoGenerateColumns="False" DataSourceID="XpoTemplete" KeyFieldName="Oid"OnBeforePerformDataSelect="gvdr_BeforePerformDataSelect" OnRowInserting="gvdr_RowInserting" ><Columns><dx:GridViewCommandColumn ShowDeleteButton="True" ShowEditButton="True" ShowNewButtonInHeader="True" VisibleIndex="0" Width="100px"></dx:GridViewCommandColumn><dx:GridViewDataTextColumn FieldName="Name" VisibleIndex="2"></dx:GridViewDataTextColumn><dx:GridViewDataTextColumn FieldName="Code" VisibleIndex="3"></dx:GridViewDataTextColumn><dx:GridViewDataTextColumn FieldName="LastVersion" VisibleIndex="4"></dx:GridViewDataTextColumn></Columns><SettingsEditing Mode="EditForm"></SettingsEditing><SettingsBehavior ConfirmDelete="True" /></dx:ASPxGridView></dx:ContentControl></ContentCollection></dx:TabPage></TabPages></dx:ASPxPageControl></DetailRow></Templates><SettingsDetail ShowDetailRow="true" AllowOnlyOneMasterRowExpanded="true" /><SettingsBehavior AllowSelectSingleRowOnly="true" /><%-- <Settings HorizontalScrollBarMode="Visible" />--%></dx:ASPxGridView>//后台代码protected void gvdr_BeforePerformDataSelect(object sender, EventArgs e){var p = (sender as ASPxGridView).GetMasterRowKeyValue();if (p != null)Session["PS"] = p.ToString();elseSession["PS"] = "-1";XpoTemplete.Criteria = CriteriaOperator.Parse("AppMoudless.Oid=?", Session["PS"].ToString()).ToString();}protected void gvdr_RowInserting(object sender, DevExpress.Web.Data.ASPxDataInsertingEventArgs e){e.NewValues["AppMoudless!Key"] = int.Parse(Session["PS"].ToString());}
<dx:GridViewDataMemoColumn FieldName="ContentAbstract" Caption="研究内容提要" Visible="false"><PropertiesMemoEdit Rows="5" MaxLength="300" ><ValidationSettings><RegularExpression ErrorText="最少100字" ValidationExpression=" ^(.|\n){0,300}$" /></ValidationSettings></PropertiesMemoEdit><EditFormSettings Visible="True" ColumnSpan="2" /></dx:GridViewDataMemoColumn>
只单行限制字数正则: ^.{100,300}$
多行限制计算字数: ^(.|\n){0,500}$
用控件自带的“MaxLength”属性控制最大值(多行)
1/导出Excle表格
<dx:ASPxGridViewExporter ID="gridExport" GridViewID="gvAll" runat="server"></dx:ASPxGridViewExporter>//后台代码protected void btnExcel_Click(object sender, EventArgs e){gridExport.WriteXlsxToResponse("立项管理台帐" + DateTime.Now.ToString("yyyyMMdd"), new XlsxExportOptionsEx { ExportType = ExportType.WYSIWYG });}
2/Word文档
<asp:Button Text="成果书WORD" runat="server" CssClass="btn btn-info" ID="btnCover" OnClick="btnCover_Click" />
后台
private static object lk = new object();protected void btnCover_Click(object sender, EventArgs e){Crack();// 破解Aspose.Wordsstring newFile = ($"~/测量成果书{DateTime.Now.ToString("yyyyMMddHHmmssms")}{new Random().Next(99999)}.doc");Aspose.Words.Document doc = new Aspose.Words.Document(Server.MapPath("~/Measure/测量成果书.doc"));lock (lk){docReplace(doc, "{Project.Name}", BindHelper.Bind(Remeasure, "Plan.Project.Name"));docReplace(doc, "{Code}", BindHelper.Bind(Remeasure, "Code"));docReplace(doc, "{Department.Name}", BindHelper.Bind(ScopeHelper.GetScope(Remeasure.Department), "Name"));docReplace(doc, "{bz}", BindHelper.Bind(Remeasure, "bz"));docReplace(doc, "{fh}", BindHelper.Bind(Remeasure, "fh"));docReplace(doc, "{sh}", BindHelper.Bind(Remeasure, "sh"));docReplace(doc, "{pz}", BindHelper.Bind(Remeasure, "pz"));docReplace(doc, "{date}", Remeasure?.UploadDate?.ToString("yyyy 年 M 月 d 日"));int ver = 'A';ver = ver + Remeasure.Approvals.Where(o => o.Result == ApprovalResult.Disagree).Count();docReplace(doc, "{ver}", Convert.ToChar(ver).ToString());string newPath = Server.MapPath(newFile);doc.Save(newPath);}Response.Redirect(newFile);}private static void Crack()//使用前调用一次即可{string[] stModule = new string[8]{"\u000E\u2008\u200A\u2001","\u000F\u2008\u200A\u2001","\u0002\u200A\u200A\u2001","\u000F","\u0006","\u000E","\u0003","\u0002"};Assembly assembly = Assembly.GetAssembly(typeof(Aspose.Words.License));Type typeLic = null, typeIsTrial = null, typeHelper = null;foreach (Type type in assembly.GetTypes()){if ((typeLic == null) && (type.Name == stModule[0])){typeLic = type;}else if ((typeIsTrial == null) && (type.Name == stModule[1])){typeIsTrial = type;}else if ((typeHelper == null) && (type.Name == stModule[2])){typeHelper = type;}}if (typeLic == null || typeIsTrial == null || typeHelper == null){throw new Exception();}object lic = Activator.CreateInstance(typeLic);int findCount = 0;foreach (FieldInfo field in typeLic.GetFields(BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance)){if (field.FieldType == typeLic && field.Name == stModule[3]){field.SetValue(null, lic);++findCount;}else if (field.FieldType == typeof(DateTime) && field.Name == stModule[4]){field.SetValue(lic, DateTime.MaxValue);++findCount;}else if (field.FieldType == typeIsTrial && field.Name == stModule[5]){field.SetValue(lic, 1);++findCount;}}foreach (FieldInfo field in typeHelper.GetFields(BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance)){if (field.FieldType == typeof(bool) && field.Name == stModule[6]){field.SetValue(null, false);++findCount;}if (field.FieldType == typeof(int) && field.Name == stModule[7]){field.SetValue(null, 128);++findCount;}}if (findCount < 5){throw new NotSupportedException("无效的版本");}}private void docReplace(Aspose.Words.Document doc, string frindText, string replaceWith){doc.Range.Replace(frindText, replaceWith, false, false);}
word文档格式:
文档:
{Project.Name}控制网
测量成果书
编号:{Code}
版本号:{ver}
编制:{bz}
复核:{fh}
审核:{sh}
批准:{pz}
中铁上海工程局集团有限公司
{department.Name}编
{date}
3/pdf
右击打印保存pdf格式
<dx:GridViewDataComboBoxColumn FieldName="SupportProjectN" VisibleIndex="6" Caption="依托项目"><PropertiesComboBox DropDownStyle="DropDown"></PropertiesComboBox></dx:GridViewDataComboBoxColumn>
DropDownStyle一定要是DropDown 不能是 DropDownlist
protected void gvAll_OnCellEditorInitialize(object sender, ASPxGridViewEditorEventArgs e){if (e.Column.FieldName == "SupportProjectN"){var cb = e.Editor as ASPxComboBox;if (cb == null)return;var project = new XPCollection<Project>(session, CriteriaOperator.Parse("StartsWith(Scope,?)", ScopeHelper.CurrentScope()));foreach (var item in project){cb.Items.Add(item.Name,item.Name);}}}
if (Oid < 0)新建时候进去;编辑时不进入
protected override void OnSaving(){base.OnSaving();if (Oid < 0){Creator = Session.FindObject<CsUser>(CriteriaOperator.Parse("LoginName=?", HttpContext.Current.User.Identity.Name));Department = ScopeHelper.GetScope(Creator.Department);}if (AcceptTime != null)if (Photo1 == null)throw new Exception("未上传受理时间照片!");if (OAuthTime != null)if (Photo2 == null)throw new Exception("未上传授权时间照片!");}
在新窗口打开
url = "window.open('" + url + "')";ASPxWebControl.RedirectOnCallback("javascript:" + url);
在原窗口打开
ASPxWebControl.RedirectOnCallback(url);
<script>function SelectAllGridLookup(){gdlp_dept.SelectAll();}</script><dx:GridViewDataColumn FieldName="SupportProjectN" VisibleIndex="6" Caption="依托工程项目" Visible="false"><EditFormSettings Visible="True" /><EditItemTemplate><dx:ASPxGridLookup ID="gdlp_dept" runat="server" SelectionMode="Multiple" ClientInstanceName="gdlp_dept" DataSourceID="XpoProject"KeyFieldName="Name" Width="200px" TextFormatString="{0}" MultiTextSeparator=", " GridViewStyles-Cell-Wrap="False" CssClass="f_l mr20" AutoGenerateColumns="False"><Columns><dx:GridViewCommandColumn ShowSelectCheckbox="True" SelectAllCheckboxMode="Page" /><dx:GridViewDataColumn FieldName="Name" Settings-AllowAutoFilter="True" ></dx:GridViewDataColumn></Columns></dx:ASPxGridLookup></EditItemTemplate></dx:GridViewDataColumn>
数据绑定 参考实例2
记得同时设置一下控件的KeyFieldName属性为你要选中的值
item 就是前端的“Name” SetSelectionByKey 所有要KeyFieldName 也是Name,和选择的FieldName一致
这样在从数据库读出来编辑绑定时才有用
protected void gvAll_HtmlDataCellPrepared(object sender, ASPxGridViewTableDataCellEventArgs e){if ((gvAll.EditingRowVisibleIndex == e.VisibleIndex && e.DataColumn.FieldName == "SupportName") && !gvAll.IsNewRowEditing){var cbl = gvAll.FindEditRowCellTemplateControl(gvAll.DataColumns["SupportProjectN"], "gdlp_dept") as ASPxGridLookup;var o = gvAll.GetRow(e.VisibleIndex) as PatentModel;var values = o?.SupportProjectN?.Split(',');if (values != null && values.Length > 0){foreach (var item in values){cbl.GridView.Selection.SetSelectionByKey(item, true);}}}}
//身份证自动填生日、性别function IDNumberBlur(s, e) {var idNum = s.GetValue();if ($.isNumeric(idNum) && idNum.length == 18) {Birthday.SetValue(new Date(idNum.substring(6, 14).replace(/^(\d{4})(\d{2})(\d{2})$/, "$1-$2-$3")));if (idNum.substring(16, 17) % 2 == 0)Sex.SetValue("女");elseSex.SetValue("男");}}<dx:GridViewDataTextColumn FieldName="IDNumber" VisibleIndex="5" Visible="false"><PropertiesTextEdit MaxLength="18"><ValidationSettings ErrorText="身份证格式不对" ><RegularExpression ErrorText="身份证格式不对" ValidationExpression="[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)" /><RequiredField IsRequired="True" ErrorText="不能为空"/></ValidationSettings></PropertiesTextEdit><EditFormSettings Visible="True" /></dx:GridViewDataTextColumn><dx:GridViewDataComboBoxColumn FieldName="Sex" VisibleIndex="6"><PropertiesComboBox ClientInstanceName="Sex"><Items><dx:ListEditItem Value="男" /><dx:ListEditItem Value="女" /></Items></PropertiesComboBox></dx:GridViewDataComboBoxColumn><dx:GridViewDataDateColumn FieldName="Birthday" VisibleIndex="7"><PropertiesDateEdit ClientInstanceName="Birthday"></PropertiesDateEdit></dx:GridViewDataDateColumn>protected void gvAll_CellEditorInitialize(object sender, ASPxGridViewEditorEventArgs e){//身份证自动填生日、性别if (e.Column.FieldName == "IDNumber"){e.Editor.SetClientSideEventHandler("LostFocus", "IDNumberBlur");}}
C#中(int)、int.Parse()、int.TryParse()和Convert.ToInt32()的区别
DateTime GraduationTime = Convert.ToDateTime(e.NewValues["GraduationTime"].ToString());int EducationOid = Convert.ToInt32(e.NewValues["Education!Key"].ToString());
//实体类
[DisplayName("受理照片")]public string _Photo1;[DisplayName("授权照片")]public string _Photo2;[DisplayName("失效PDF"), Size(1000)]public string _Photo5;[DisplayName("备注PDF"), Size(1000)]public string _Photo6;[DisplayName("受理照片"), NonPersistent]public byte[] Photo1_1{set{var url = HttpContext.Current;if (value != null){byte[] array = value;string path = url.Server.MapPath("~/Images/PhotoImage/" + PatentName + "-" + PatentNo + "受理" + ".jpg");FileStream fs = new FileStream(path, FileMode.Create);fs.Write(value, 0, value.Length);fs.Close(); ;_Photo1 = path;}else{try{string path = url.Server.MapPath("~/Images/PhotoImage/" + PatentName + "-" + PatentNo + "受理" + ".jpg");System.IO.File.Delete(path);_Photo1 = null;}catch { _Photo1 = null; }}}get { return null; }}[DisplayName("授权照片"), NonPersistent]public byte[] Photo2_2{set{var url = HttpContext.Current;if (value != null){byte[] array = value;string path = url.Server.MapPath("~/Images/PhotoImage/" + PatentName + "-" + PatentNo + "授权" + ".jpg");FileStream fs = new FileStream(path, FileMode.Create);fs.Write(value, 0, value.Length);fs.Close();_Photo2 = path;}else{try{string path = url.Server.MapPath("~/Images/PhotoImage/" + PatentName + "-" + PatentNo + "授权" + ".jpg");System.IO.File.Delete(path);_Photo2 = null;}catch { _Photo2 = null; }}}get { return null; }}//[DisplayName("受理照片"), NonPersistent]//public byte[] Photo1//{// set// {// var url = HttpContext.Current;// if (value != null)// {// byte[] array = value;// string path = url.Server.MapPath("~/Images/PhotoImage/" + PatentName + "-" + PatentNo + "受理" + ".jpg");// FileStream fs = new FileStream(path, FileMode.Create);// fs.Write(value, 0, value.Length);// fs.Close(); ;// _Photo1 = path;// }// else// {// try// {// string path = url.Server.MapPath("~/Images/PhotoImage/" + PatentName + "-" + PatentNo + "受理" + ".jpg");// System.IO.File.Delete(path);// _Photo1 = null;// }// catch { _Photo1 = null; }// }// }// get// {// var url = HttpContext.Current;// try// {// string path = _Photo1;// FileStream fs = new FileStream(path, FileMode.Open);// long size = fs.Length;// byte[] array = new byte[size];// fs.Read(array, 0, array.Length);// fs.Close();// return array;// }// catch(Exception e)// { return null; }// }//}//[DisplayName("授权照片"), NonPersistent]//public byte[] Photo2//{// set// {// var url = HttpContext.Current;// if (value != null)// {// byte[] array = value;// string path = url.Server.MapPath("~/Images/PhotoImage/" + PatentName + "-" + PatentNo + "授权" + ".jpg");// FileStream fs = new FileStream(path, FileMode.Create);// fs.Write(value, 0, value.Length);// fs.Close();// _Photo2 = path;// }// else// {// try// {// string path = url.Server.MapPath("~/Images/PhotoImage/" + PatentName + "-" + PatentNo + "授权" + ".jpg");// System.IO.File.Delete(path);// _Photo2 = null;// }// catch { _Photo2 = null; }// }// }// get// {// var url = new System.Web.UI.Page();// try// {// string path = _Photo2;// FileStream fs = new FileStream(path, FileMode.Open);// long size = fs.Length;// byte[] array = new byte[size];// fs.Read(array, 0, array.Length);// fs.Close();// return array;// }// catch { return null; }// }//}[DisplayName("失效PDF"), NonPersistent]public string Photo3{set{var url = HttpContext.Current;if (value != null){try{string date = DateTime.Now.ToString("yyyyMMddHHmmss");string path = url.Server.MapPath("~/Images/PhotoImage/" + PatentName + "-" + PatentNo + "PDF版专利证书扫描件"+ date+ ".pdf");//path = pathSystem.IO.File.Move(value, path);_Photo5 = path;}catch (Exception e){}}}get{return _Photo5;}}[DisplayName("备注PDF"), NonPersistent]public string Photo4{set{var url = HttpContext.Current;if (value != null){try{string date = DateTime.Now.ToString("yyyyMMddHHmmss");string path = url.Server.MapPath("~/Images/PhotoImage/" + PatentName + "-" + PatentNo + "其他证明材料扫描件" + date + ".pdf");System.IO.File.Move(value, path);_Photo6 = path;}catch (Exception e){}}}get{return _Photo6;}}
//照片控件
<dx:GridViewDataBinaryImageColumn FieldName="Photo1_1" Visible="false" VisibleIndex="18" Caption="受理照片"><EditFormSettings Visible="True" /><PropertiesBinaryImage ImageHeight="100px" ImageWidth="90px"><ValidationSettings><RequiredField IsRequired="true" ErrorText="不能为空" /></ValidationSettings><EditingSettings Enabled="true" UploadSettings-UploadValidationSettings-MaxFileSize="2097152"><UploadSettings><UploadValidationSettings MaxFileSize="2097152"></UploadValidationSettings></UploadSettings></EditingSettings></PropertiesBinaryImage></dx:GridViewDataBinaryImageColumn><dx:GridViewDataBinaryImageColumn FieldName="Photo2_2" Visible="false" VisibleIndex="19" Caption="专利照片"><EditFormSettings Visible="True" /><PropertiesBinaryImage ImageHeight="100px" ImageWidth="90px"><EditingSettings Enabled="true" UploadSettings-UploadValidationSettings-MaxFileSize="2097152"><UploadSettings><UploadValidationSettings MaxFileSize="2097152"></UploadValidationSettings></UploadSettings></EditingSettings></PropertiesBinaryImage></dx:GridViewDataBinaryImageColumn>
//实体类中注释Photo1、Photo2两张照片属性运行的话,会在初始化的时候就get图片;导致加载速度很慢,解决的方法就是在get的时候,不加载,在编辑单行数据的时候加载对应图片!所以重新写了Photo1_1和Photo2_2的属性,get的时候返回null,自定义编辑的时候获取图片代码如下:
protected void gvAll_CellEditorInitialize(object sender, ASPxGridViewEditorEventArgs e){if (e.Column.FieldName == "Photo1_1"){var url = HttpContext.Current;try{var m = session.FindObject<PatentModel>(CriteriaOperator.Parse("Oid=?", e.KeyValue.ToString()));string path = m._Photo1;FileStream fs = new FileStream(path, FileMode.Open);long size = fs.Length;byte[] array = new byte[size];fs.Read(array, 0, array.Length);fs.Close();e.Editor.Value = array;}catch{ e.Editor.Value = null; }}if (e.Column.FieldName == "Photo2_2"){var url = HttpContext.Current;try{var m = session.FindObject<PatentModel>(CriteriaOperator.Parse("Oid=?", e.KeyValue.ToString()));string path = m._Photo2;FileStream fs = new FileStream(path, FileMode.Open);long size = fs.Length;byte[] array = new byte[size];fs.Read(array, 0, array.Length);fs.Close();e.Editor.Value = array;}catch{ e.Editor.Value = null; }}}
//如果在按钮列自定义增加两个按钮,点击跳转对应的图片链接,则JS回调中获取不到自定义的名称组成的链接;只能在后台的回调中跳转,代码如下:
//首先增加隐藏域(重点)<dx:ASPxHiddenField ID="HF" runat="server" ClientIDMode="Static"></dx:ASPxHiddenField>//控件:<dx:GridViewCommandColumn ShowDeleteButton="true" ShowNewButtonInHeader="true" ShowEditButton="true" Width="160px"><CustomButtons><dx:GridViewCommandColumnCustomButton ID="btnView" Text="详情" ></dx:GridViewCommandColumnCustomButton><%--<dx:GridViewCommandColumnCustomButton ID="btnSubmit" Text="提交"></dx:GridViewCommandColumnCustomButton>--%><dx:GridViewCommandColumnCustomButton ID="btnphoto3" Text="受理照片" ></dx:GridViewCommandColumnCustomButton><dx:GridViewCommandColumnCustomButton ID="btnphoto4" Text="授权照片"></dx:GridViewCommandColumnCustomButton></CustomButtons></dx:GridViewCommandColumn>//JS函数function gv_OnCustomButtonClick(s, e){if (e.buttonID == "btnView"){window.open('View.aspx?id=' + s.GetRowKey(e.visibleIndex));}else if (e.buttonID == "btnSubmit"){if (confirm("确认提交通过此条信息?")){s.PerformCallback(s.GetRowKey(e.visibleIndex));}}else if (e.buttonID == "btnphoto3"){//window.open('../Images/PhotoImage/' + e.text + "-" + e.text + "受理.jpg");//这种方法获取不到名称组成的链接HF.Set("Photo3Oid", s.GetRowKey(e.visibleIndex));gvAll.PerformCallback("Photo3View");}else if (e.buttonID == "btnphoto4"){HF.Set("Photo4Oid", s.GetRowKey(e.visibleIndex));gvAll.PerformCallback("Photo4View");}}//后台回调protected void gvAll_CustomCallback(object sender, ASPxGridViewCustomCallbackEventArgs e){if (e.Parameters == "Go-1"){gvAll.PageIndex = -1;gvAll.DataBind();}else if (e.Parameters == "Photo3View"){var pat = session.FindObject<PatentModel>(CriteriaOperator.Parse("Oid=?", HF.Get("Photo3Oid")));//string url = "../Images/PhotoImage/" + pat.PatentName + " - " + pat.PatentNo + "受理.jpg";string url = TechManager.Module.Engine.PatentPhotoHelper.GetPhotoName(pat._Photo1);url = "window.open('" + url + "')";ASPxWebControl.RedirectOnCallback("javascript:"+url);}else if (e.Parameters == "Photo4View"){var pat = session.FindObject<PatentModel>(CriteriaOperator.Parse("Oid=?", HF.Get("Photo4Oid")));string url = TechManager.Module.Engine.PatentPhotoHelper.GetPhotoName(pat._Photo2);url = "window.open('" + url + "')";ASPxWebControl.RedirectOnCallback("javascript:" + url);}}//如果存在修改变更图片,因为图片保存的是byte格式;所以gvAll_RowUpdating函数中:m.Photo1_1 = (byte[])e.NewValues["Photo1_1"];m.Photo2_2 = (byte[])e.NewValues["Photo2_2"];
上传文件(PDF)控件
//控件//AllowedFileExtensions=".pdf"控制了文件上传的格式<dx:GridViewDataColumn FieldName="Photo3" Visible="false" VisibleIndex="20" Caption="PDF版专利证书扫描件"><EditFormSettings Visible="True" /><EditItemTemplate><dx:ASPxUploadControl ID="upload1" ClientInstanceName="upload1" runat="server" ShowUploadButton="True" UploadButton-Text="上传"UploadMode="Advanced" ShowProgressPanel="True" Width="280px" CssClass="f_l" Theme="Aqua" OnFileUploadComplete="upload1_FileUploadComplete"><ValidationSettings AllowedFileExtensions=".pdf"></ValidationSettings><AdvancedModeSettings EnableFileList="True" EnableMultiSelect="False" EnableDragAndDrop="True" ></AdvancedModeSettings><ClientSideEvents FileUploadComplete="onFileUploadComplete" /></dx:ASPxUploadControl></EditItemTemplate></dx:GridViewDataColumn><dx:GridViewDataBinaryImageColumn FieldName="Photo4" Visible="false" VisibleIndex="21" Caption="其他证明材料扫描件"><EditFormSettings Visible="True" /><EditItemTemplate><dx:ASPxUploadControl ID="upload2" ClientInstanceName="upload2" runat="server" ShowUploadButton="True" UploadButton-Text="上传"UploadMode="Advanced" ShowProgressPanel="True" Width="280px" CssClass="f_l" Theme="Aqua" OnFileUploadComplete="upload2_FileUploadComplete">-----------------------------------------------------------<ValidationSettings AllowedFileExtensions=".pdf"></ValidationSettings><AdvancedModeSettings EnableFileList="True" EnableMultiSelect="False" EnableDragAndDrop="True" ></AdvancedModeSettings><ClientSideEvents FileUploadComplete="onFileUploadComplete1" />--------------------------------------------------------------------------------</dx:ASPxUploadControl></EditItemTemplate></dx:GridViewDataBinaryImageColumn>//JS函数//onFileUploadComplete 相当于GridView中的CallBackfunction onFileUploadComplete(s, e) {if (e.callbackData) {HF.Set("Photo3", e.callbackData);}}function onFileUploadComplete1(s, e) {if (e.callbackData) {HF.Set("Photo4", e.callbackData);}}//后台函数// System.IO.File.Move是将上传的文件移动到临时文件夹并再加后缀名;因为存在的是临时文件,所以如果测试的时候文件上传成功了,在还没有保存之前就自动删除,则改变它的后缀名,如e.UploadedFile.FileNameInStorage + ".tt";改为.tt。e.CallbackData返回的是文件路径;protected void upload1_FileUploadComplete(object sender, FileUploadCompleteEventArgs e){if (e.IsValid && !string.IsNullOrEmpty(e.UploadedFile.FileNameInStorage)){System.IO.File.Move(e.UploadedFile.FileNameInStorage, e.UploadedFile.FileNameInStorage+".pdf");e.CallbackData = e.UploadedFile.FileNameInStorage + ".pdf";}}protected void upload2_FileUploadComplete(object sender, FileUploadCompleteEventArgs e){if (e.IsValid && !string.IsNullOrEmpty(e.UploadedFile.FileNameInStorage)){System.IO.File.Move(e.UploadedFile.FileNameInStorage, e.UploadedFile.FileNameInStorage + ".tt");e.CallbackData = e.UploadedFile.FileNameInStorage + ".tt";}}//这个时候文件还没有保存到我们希望的地方;还在临时文件夹里面,需要我们重新移动文件并重命名;所以在gvAll_RowInserting和gvAll_RowUpdating中都写下这样的代码;把临时路径给属性,在实体类中移动文件并重命名。if (HF.Contains("Photo3")){m.Photo3 = HF.Get("Photo3").ToString();}if (HF.Contains("Photo4")){m.Photo4 = HF.Get("Photo4").ToString();}
function gv_OnCustomButtonClick(s, e){if (e.buttonID == "btnView"){window.open('View.aspx?id=' + s.GetRowKey(e.visibleIndex));}else if (e.buttonID == "btnSubmit"){if (confirm("确认提交通过此条信息?")){s.PerformCallback(s.GetRowKey(e.visibleIndex));}}else if (e.buttonID == "btnphoto3"){//window.open('../Images/PhotoImage/' + e.text + "-" + e.text + "受理.jpg");HF.Set("Photo3Oid", s.GetRowKey(e.visibleIndex));gvAll.PerformCallback("Photo3View");}}protected void gvAll_CustomCallback(object sender, ASPxGridViewCustomCallbackEventArgs e){if (e.Parameters == "Go-1"){gvAll.PageIndex = -1;gvAll.DataBind();}else if (e.Parameters == "Photo3View"){var pat = session.FindObject<PatentModel>(CriteriaOperator.Parse("Oid=?", HF.Get("Photo3Oid")));//string url = "../Images/PhotoImage/" + pat.PatentName + " - " + pat.PatentNo + "受理.jpg";string url = TechManager.Module.Engine.PatentPhotoHelper.GetPhotoName(pat._Photo1);url = "window.open('" + url + "')";ASPxWebControl.RedirectOnCallback("javascript:"+url);} else{//提交、、}
gv.SettingsPager.Mode = 0;
var obj= (sender as ASPxGridView).GetRow(e.VisibleIndex) as InspectionMeasure;var masterKey = ((sender) as ASPxGridView).GetMasterRowKeyValue();var o = session.FindObject<EquipmentMeasure>(CriteriaOperator.Parse("Oid=?", masterKey));var InspectDate = gvAll.GetRowValues(e.VisibleIndex, "InspectDate");var eq = gvAll.GetRow(e.VisibleIndex) as EquipmentMeasure;
/// <summary>/// 人员表当中部门排序/// </summary>private static ArrayList CompanyArr;protected void gvAll_CustomColumnSort(object sender, DevExpress.Web.CustomColumnSortEventArgs e){CompanyArr = CompanyArr ?? new ArrayList(new XPCollection<Department>(session, CriteriaOperator.Parse("1=1"), new SortProperty("Order", DevExpress.Xpo.DB.SortingDirection.Ascending) , new SortProperty("FullCode", DevExpress.Xpo.DB.SortingDirection.Ascending)).Select(o => o.Name).ToArray());CustomSortHelper.CustomFieldSort(e, "DepartmentCompany.Name|Department.Name", CompanyArr, CompanyArr);}
var gvC = gvAll.FindControl("gv") as ASPxGridView;var v = (gvC.GetRow(gvC.EditingRowVisibleIndex) as TeamImplement)?.Project?.Oid;Repeater rep = e.Item.FindControl("rptList") as Repeater;//找到里层的repeater对象Detail rowv = (Detail)e.Item.DataItem;//找到分类Repeater关联的数据项//int typeid = Convert.ToInt32(rowv["Oid"]); //获取填充子类的idvar list = new XPCollection<DetailList>(session, CriteriaOperator.Parse("Detail.Oid=?", rowv.Oid));