[关闭]
@Aiti 2018-05-28T01:19:06.000000Z 字数 35914 阅读 671

WebForm添加按钮标签/添加富文本/GridView中下拉框联动

未分类
protected void gvAll_CellEditorInitialize(object sender, ASPxGridViewEditorEventArgs e)
参数sender:指当前控件;
(sender as ASPxGridView);(sender as ASPxComboBox);等等!
参数e:当前行值;

1.添加富文本

  1. <dx:GridViewDataColumn FieldName="Content" VisibleIndex="6" >
  2. <EditFormSettings Visible="True" ColumnSpan="2" />
  3. <EditItemTemplate>
  4. <dx:ASPxHtmlEditor ID="html" runat="server" Html='<%# Bind("Content") %>'>
  5. <Settings AllowHtmlView="false" />
  6. <SettingsDialogs>
  7. <InsertImageDialog>
  8. <SettingsImageUpload UploadFolder="StandardsInfo/UploadFiles/Images/">
  9. <ValidationSettings AllowedFileExtensions=".jpe,.jpeg,.jpg,.gif,.png,.webp" MaxFileSize="500000">
  10. </ValidationSettings>
  11. </SettingsImageUpload>
  12. </InsertImageDialog>
  13. </SettingsDialogs>
  14. </dx:ASPxHtmlEditor>
  15. </EditItemTemplate>
  16. </dx:GridViewDataColumn>

2.将枚举类做成多选框

//控件直接做成多选框

  1. <div class="search-name">项目状态:</div>
  2. <dx:ASPxCheckBoxList runat="server" ID="chxPStatus" CssClass="inb" RepeatDirection="Horizontal" ClientIDMode="Static">
  3. </dx:ASPxCheckBoxList>
  4. <dx:ASPxCheckBox runat="server" ID="AllPStatus" ClientIDMode="Static" Text="全部" CssClass="inb" Checked="true">
  5. <ClientSideEvents CheckedChanged="AllPStatusChange" />
  6. </dx:ASPxCheckBox>
  7. </div>
  8. if (!IsPostBack)
  9. {
  10. EnumHelper.SetListControl(chxPStatus, typeof(ProjectStatus));
  11. chxPStatus.Items[0].Selected = chxPStatus.Items[1].Selected = true;
  12. }

//控件里面套控件直接做成多选框

  1. <dx:GridViewDataColumn FieldName="Properties" Caption="属性" VisibleIndex="4">
  2. <EditItemTemplate>
  3. <dx:ASPxCheckBoxList runat="server" ID="chxProperties" >
  4. </dx:ASPxCheckBoxList>
  5. </EditItemTemplate>
  6. </dx:GridViewDataColumn>
  7. protected void gvAll_HtmlDataCellPrepared(object sender, ASPxGridViewTableDataCellEventArgs e)
  8. {
  9. if (gvAll.EditingRowVisibleIndex == e.VisibleIndex && !gvAll.IsNewRowEditing)
  10. if (e.DataColumn.FieldName == "Properties")
  11. {
  12. var cbl = gvAll.FindEditRowCellTemplateControl(gvAll.DataColumns["Properties"], "chxProperties") as ASPxCheckBoxList;
  13. if (cbl != null)
  14. EnumHelper.SetListControl(cbl, typeof(ArticleProperty));
  15. }
  16. }

这只是显示出来;然后再绑定数据;新建,编辑,保存更新时都要重新保存数据
修改事件
1.首先增加上传数据到数据库的事件

  1. protected void gvAll_RowInserting(object sender, DevExpress.Web.Data.ASPxDataInsertingEventArgs e)
  2. {
  3. e.NewValues["Properties"] = GetProperties();
  4. }

2.添加更新数据的事件

  1. protected void gvAll_RowUpdating(object sender, DevExpress.Web.Data.ASPxDataUpdatingEventArgs e)
  2. {
  3. e.NewValues["Properties"] = GetProperties();
  4. }

3.把相同的代码块做成一个返回函数;获取选择的多选框

  1. private ArticleProperty GetProperties(){
  2. var cbl = gvAll.FindEditRowCellTemplateControl(gvAll.DataColumns["Properties"], "chxProperties") as ASPxCheckBoxList;
  3. ArticleProperty appLevels = 0;
  4. foreach (ListEditItem item in cbl.SelectedItems)
  5. {
  6. appLevels += int.Parse(item.Value.ToString());
  7. }
  8. return appLevels;
  9. }

4.这时候会发现“新建”时;多选框不显示;编辑更新保存数据时不成功;主要原因是:新建时,gvAll_HtmlDataCellPrepared事件中判断条件使得CheckBoxList没有初始化;所以多选框不显示;编辑更新数据不成功是因为每次进入返回函数时,之前都进入了gvAll_HtmlDataCellPrepared函数会进入if里面,多选框会被初始化;所以前端选择的都被初始化了。

  • 解决方法:

建立CheckBoxList自己的事件初始化多选框;

  1. //前端代码
  2. <dx:GridViewDataColumn FieldName="Properties" Caption="属性" VisibleIndex="11">
  3. <EditItemTemplate>
  4. <dx:ASPxCheckBoxList runat="server" ID="chxProperties" RepeatLayout="UnorderedList" OnInit="chxProperties_Init">
  5. </dx:ASPxCheckBoxList>
  6. </EditItemTemplate>
  7. </dx:GridViewDataColumn>
  8. //后台代码
  9. protected void chxProperties_Init(object sender, EventArgs e)
  10. {
  11. var cbl = sender as ASPxCheckBoxList;// gvAll.FindEditRowCellTemplateControl(gvAll.DataColumns["Properties"], "chxProperties") as ASPxCheckBoxList; //sender as ASPxCheckBoxList;
  12. if (cbl != null)
  13. EnumHelper.SetListControl(cbl, typeof(ArticleProperty));
  14. }

新建时不进入gvAll_HtmlDataCellPrepared函数初始化了;直接保存更新的数据;编辑时;进入gvAll_HtmlDataCellPrepared;绑定选择的多选框;所以修改gvAll_HtmlDataCellPrepared

  1. protected void gvAll_HtmlDataCellPrepared(object sender, ASPxGridViewTableDataCellEventArgs e)
  2. {
  3. if ((gvAll.EditingRowVisibleIndex == e.VisibleIndex && e.DataColumn.FieldName == "Properties") && !gvAll.IsNewRowEditing)
  4. {
  5. var cbl = gvAll.FindEditRowCellTemplateControl(gvAll.DataColumns["Properties"], "chxProperties") as ASPxCheckBoxList;
  6. var o = gvAll.GetRow(e.VisibleIndex) as Article;
  7. for (int i = 0; i < cbl.Items.Count; i++)
  8. {
  9. if (o.Properties.HasFlag((ArticleProperty)int.Parse(cbl.Items[i].Value.ToString())))
  10. cbl.Items[i].Selected = true;
  11. }
  12. }
  13. }
  • 重点

看实体类

  1. [DisplayName("属性")]
  2. public string Properties;

看枚举类

  1. //[Flags]
  2. public enum ArticleProperty
  3. {
  4. [Description("热门")]
  5. Hot = 0x1,
  6. [Description("推荐")]
  7. Recommoned = 0x2,
  8. [Description("通知")]
  9. Notice = 0x4,
  10. [Description("图片")]
  11. Picture = 0x8,
  12. [Description("介绍信息")]
  13. Intro = 0x16
  14. }

使用的是16进制表示的变量;当选择变量加起来超过16的话,保存过后再编辑就显示的不再是之前选择的;或者显示数字;

  • 再次修改

先修改类

  1. [NonPersistent]
  2. public string PropertieNames
  3. {
  4. get
  5. {
  6. //1,3,5
  7. var st = "";
  8. var values = Properties?.Split(',');
  9. if (values != null && values[0].Length > 0)
  10. {
  11. var Leg = values.Length;
  12. foreach (var inte in values)
  13. {
  14. st += Enum.Parse(typeof(ArticleProperty), inte);
  15. if (--Leg > 0)
  16. st += ',';
  17. }
  18. }
  19. return st;
  20. }
  21. }

枚举类

  1. public enum ArticleProperty
  2. {
  3. 热门 = 1,
  4. 推荐 = 2,
  5. 通知 = 3,
  6. 图片 = 4,
  7. 介绍信息 = 5
  8. }

再修该事件绑定的格式

  1. protected void gvAll_HtmlDataCellPrepared(object sender, ASPxGridViewTableDataCellEventArgs e)
  2. {
  3. if ((gvAll.EditingRowVisibleIndex == e.VisibleIndex && e.DataColumn.FieldName == "PropertieNames") && !gvAll.IsNewRowEditing)
  4. {
  5. var cbl = gvAll.FindEditRowCellTemplateControl(gvAll.DataColumns["Properties"], "chxProperties") as ASPxCheckBoxList;
  6. var o = gvAll.GetRow(e.VisibleIndex) as Article;
  7. //for (int i = 0; i < cbl.Items.Count; i++)
  8. //{
  9. // if (o.Properties.HasFlag((ArticleProperty)int.Parse(cbl.Items[i].Value.ToString())))
  10. // cbl.Items[i].Selected = true;
  11. //}
  12. var values = o?.Properties?.Split(',');
  13. if (values != null && values[0].Length>0)
  14. {
  15. foreach (ListEditItem item in cbl.Items)
  16. {
  17. if (values.Contains(item.Value))
  18. item.Selected = true;
  19. }
  20. }
  21. }
  22. }
  23. protected void chxProperties_Init(object sender, EventArgs e)
  24. {
  25. var cbl = sender as ASPxCheckBoxList;
  26. // gvAll.FindEditRowCellTemplateControl(gvAll.DataColumns["Properties"], "chxProperties") as ASPxCheckBoxList;
  27. if (cbl != null)
  28. {
  29. //EnumHelper.SetListControl(cbl, typeof(ArticleProperty));
  30. foreach (var value in Enum.GetValues(typeof(ArticleProperty)))
  31. {
  32. var type = (ArticleProperty)value;
  33. cbl.Items.Add(type.ToString(), ((int)type).ToString());
  34. }
  35. }
  36. }
  37. private string GetProperties()
  38. {
  39. var cbl = gvAll.FindEditRowCellTemplateControl(gvAll.DataColumns["Properties"], "chxProperties") as ASPxCheckBoxList;
  40. var count = cbl.SelectedItems.Count;
  41. if (count <= 0) return "";
  42. var buffer = new StringBuilder();
  43. foreach (ListEditItem item in cbl.SelectedItems)
  44. {
  45. buffer.Append(item.Value);
  46. if (--count > 0)
  47. buffer.Append(',');
  48. }
  49. return buffer.ToString();
  50. }

至此完成了枚举类在GridView控件中变成多选框的问题!!!

3.Contains包含关系;字符包含字符

  1. <asp:Label runat="server" Text='<%# Eval("PropertieNames").ToString().Contains("通知")?"通知":"" %> '></asp:Label>

4.添加点击标签

  1. <script src="../assets/global/plugins/jquery.min.js" type="text/javascript"></script>
  2. <script type="text/javascript">
  3. jQuery(function ($) {
  4. $(function()
  5. {
  6. $(".btn-group").each(function () {
  7. if(HF.Get($(this).data("group")))
  8. {
  9. $(this).find(".btn[data-criteria='"+HF.Get($(this).data("group"))+"']").addClass("focus");
  10. }else
  11. {
  12. $(this).find(".btn:first").addClass("focus");
  13. }
  14. });
  15. });
  16. $(".btn-group .btn").click(function()
  17. {
  18. $(".btn-group .btn").click(function () {
  19. $(this).parent().find(".btn").removeClass("focus");
  20. $(this).addClass("focus");
  21. HF.Set($(this).parent().data("group"), $(this).data("criteria"));
  22. gvAll.PerformCallback("Go-1"); //转到第一页
  23. });
  24. var type = $(this).data("criteria");
  25. switch (type) {
  26. case "Day":
  27. gvD.SetVisiable = true;
  28. gvW.SetVisiable = false;
  29. gvM.SetVisiable = false;
  30. //document.getElementById("gvD").style.display = "block";
  31. //document.getElementById("gvW").style.display = "none";
  32. //document.getElementById("gvM").style.display = "none";
  33. break;
  34. case "Week":
  35. gvD.SetVisiable = false;
  36. gvW.SetVisiable = true;
  37. gvM.SetVisiable = false;
  38. break;
  39. case "Month":
  40. gvD.SetVisiable = false;
  41. gvW.SetVisiable = false;
  42. gvM.SetVisiable = true;
  43. break;
  44. }
  45. });
  46. });
  47. </script>
  1. <div class="panel panel-default blue">
  2. <dx:ASPxHiddenField ID="HF" runat="server" ClientIDMode="Static" ></dx:ASPxHiddenField>
  3. <div class="panel-body">
  4. <div class="row">
  5. <span class="ml10">报告类型:</span>
  6. <div class="btn-group" data-group="flow">
  7. <button type="button" class="btn btn-default" data-criteria="Day">工作日报</button>
  8. <button type="button" class="btn btn-default" data-criteria="Week">工作周报</button>
  9. <button type="button" class="btn btn-default" data-criteria="Month">工作月报</button>
  10. </div>
  11. </div>
  12. </div>
  13. </div>
  14. <dx:ASPxGridView runat="server" ID="gvD" KeyFieldName="Oid" DataSourceID="XpoD" Caption="工作日报" ></dx:ASPxGridView>
  15. <dx:ASPxGridView runat="server" ID="gvD" KeyFieldName="Oid" DataSourceID="XpoW" Caption="工作周报" ></dx:ASPxGridView>
  16. <dx:ASPxGridView runat="server" ID="gvD" KeyFieldName="Oid" DataSourceID="XpoM" Caption="工作月报" ></dx:ASPxGridView>

5.如果不是改变GridView;而是像改变查询条件则:

  1. if (!HF.Contains("flow"))
  2. {
  3. HF.Set("flow", "ALL");
  4. }
  5. if (!HF.Contains("status"))
  6. {
  7. HF.Set("status", "ALL");
  8. }
  9. switch (HF.Get("flow").ToString())
  10. {
  11. case "MY":
  12. op = CriteriaOperator.And(op, CriteriaOperator.Parse($"Actor='{User.Identity.Name}'"));
  13. break;
  14. case "PASS":
  15. op = CriteriaOperator.And(op, CriteriaOperator.Parse($"Oid IN ({getCurrentUserProcessedOids("ProjectApproval", true)})"));
  16. break;
  17. }

5.GridView中两个下拉框联动

1、在GridView中两个下拉框;工作面随隧道改变而改变;所以在隧道的ComboBox中加SelectedIndexChanged属性;两个验证方式都是动态的且不为空;之所以加Init属性;是因为在编辑时;隧道名已经存在;不存在变动;所以工作面的选项不会出现;加了之后也会调用函数对工作面数据源绑定;

  1. <dx:GridViewDataComboBoxColumn FieldName="TunnelsName!Key" Caption="隧道名称" >
  2. <PropertiesComboBox TextField="Name" ValueField="Oid" DataSourceID="XpoTunnels">
  3. <ClientSideEvents SelectedIndexChanged ="function(s,e){ Surface.PerformCallback(s.GetValue()); }" Init="function(s,e){ Surface.PerformCallback(s.GetValue()); }" />
  4. <ValidationSettings Display="Dynamic">
  5. <RequiredField IsRequired="true" />
  6. </ValidationSettings>
  7. </PropertiesComboBox>
  8. </dx:GridViewDataComboBoxColumn>
  9. <dx:GridViewDataComboBoxColumn FieldName="SurfaceName!Key" Caption="隧道工作面" >
  10. <PropertiesComboBox TextField="Name" ValueField="Oid" DataSourceID="XpoSurface" ClientInstanceName="Surface">
  11. <ValidationSettings Display="Dynamic">
  12. <RequiredField IsRequired="true" />
  13. </ValidationSettings>
  14. </PropertiesComboBox>
  15. </dx:GridViewDataComboBoxColumn>

2、通过初始化编辑方法调用Surface的回调函数;对XpoSurface绑定数据源;变量v是获取当前编辑行的工作面Oid;新建时gvAll.EditingRowVisibleIndex为负值;v=null;if条件判断是新建时e.Parameter为空字符;编辑时获取的是前台传过来的当前隧道Oid;新建时,l=0;编辑时,l为Item的长度;for循环对ComboBox绑定之前已选择的值!

  1. protected void gvAll_CellEditorInitialize(object sender, ASPxGridViewEditorEventArgs e)
  2. {
  3. if (e.Column.FieldName == "SurfaceName!Key")
  4. {
  5. (e.Editor as ASPxComboBox).Callback += Surface_Callback;
  6. }
  7. }
  8. protected void Surface_Callback(object sender, CallbackEventArgsBase e)
  9. {
  10. var v = (gvAll.GetRow(gvAll.EditingRowVisibleIndex) as TunnelTest)?.SurfaceName?.Oid;
  11. if (e.Parameter != "") {
  12. XpoSurface.Criteria = $"Tunnels.Oid={e.Parameter}";
  13. (sender as ASPxComboBox).DataBind();
  14. }
  15. var l = (sender as ASPxComboBox).Items.Count;
  16. for (var i = 0; i < l; i++)
  17. {
  18. if ((int)(sender as ASPxComboBox).Items[i].Value == v)
  19. (sender as ASPxComboBox).Items[i].Selected = true;
  20. }
  21. }

总结:
通过隧道的ASPxComboBox的回调调用工作面的自定义函数;
即:(e.Editor as ASPxComboBox).Callback += Surface_Callback;
2.通过gvAll.EditingRowVisibleIndex获取当前行数;再通过gvAll.GetRow获取当前行数据;
3.还能通过
XpoSurface.Criteria = $"Tunnels.Oid={e.Parameter}";
(sender as ASPxComboBox).DataBind();这种方式绑定数据源!!!!!

6.在绑定数据源的下拉框中添加一项

  1. <dx:GridViewDataComboBoxColumn FieldName="ProjectApproval!Key" Caption="依托科研工法">
  2. <PropertiesComboBox DataSourceID="XpoProject" TextField="ProjectName" ValueField="Oid"></PropertiesComboBox>
  3. </dx:GridViewDataComboBoxColumn>
  4. protected void gvAll_OnCellEditorInitialize(object sender, ASPxGridViewEditorEventArgs e)
  5. {
  6. if (e.Column.FieldName == "SupportProject!Key")
  7. {
  8. AddOtherItem(e.Editor);
  9. }
  10. else if (e.Column.FieldName == "ProjectApproval!Key")
  11. {
  12. AddOtherItem(e.Editor);
  13. }
  14. }
  15. private void AddOtherItem(object editor)
  16. {
  17. var cb = editor as ASPxComboBox;
  18. if (cb == null) return;
  19. cb.DataBound += (s, args) =>
  20. {
  21. var item = cb.Items.Add("其他", 0);
  22. //if (cb.Value == null)
  23. // cb.SelectedItem = item;
  24. };
  25. }

7.编辑模板中添加图片上传功能

控件:

  1. <dx:GridViewDataBinaryImageColumn FieldName="Photo1" Visible="false" Caption="受理时间照片">
  2. <EditFormSettings Visible="True" />
  3. <PropertiesBinaryImage ImageHeight="100px" ImageWidth="90px">
  4. <EditingSettings Enabled="true" UploadSettings-UploadValidationSettings-MaxFileSize="5242880"/>
  5. </PropertiesBinaryImage>
  6. </dx:GridViewDataBinaryImageColumn>

实体类中绑定

  1. [DisplayName("受理照片"), NonPersistent]
  2. public byte[] Photo1
  3. {
  4. set {
  5. var url = new System.Web.UI.Page();
  6. if (value != null)
  7. {
  8. byte[] array = value;
  9. string path = url.Server.MapPath("~/Images/PhotoImage/" + PatentName + "-" + PatentNo + "受理" + ".jpg");
  10. FileStream fs = new FileStream(path, FileMode.Create);
  11. fs.Write(value, 0, value.Length);
  12. fs.Close();
  13. }
  14. else
  15. {
  16. try
  17. {
  18. string path = url.Server.MapPath("~/Images/PhotoImage/" + PatentName + "-" + PatentNo + "受理" + ".jpg");
  19. System.IO.File.Delete(path);
  20. }
  21. catch { }
  22. }
  23. }
  24. get {
  25. var url = new System.Web.UI.Page();
  26. try
  27. {
  28. string path = url.Server.MapPath("~/Images/PhotoImage/" + PatentName + "-" + PatentNo + "受理" + ".jpg");
  29. FileStream fs = new FileStream(path, FileMode.Open);
  30. long size = fs.Length;
  31. byte[] array = new byte[size];
  32. fs.Read(array, 0, array.Length);
  33. fs.Close();
  34. return array;
  35. }
  36. catch { return null; }
  37. }
  38. }

8.dx:GridView 某列 加链接跳转并带参数

第一种(传递的参数在数据源实体类中)

  1. <dx:GridViewDataTextColumn FieldName="Name" VisibleIndex="1" Caption="项目名称" >
  2. <DataItemTemplate>
  3. <asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl='<%# "~/Projects/ViewAll.aspx?id="+ Eval("Oid").ToString() %>' Text='<%# Eval("Name") %>'></asp:HyperLink>
  4. </DataItemTemplate>
  5. </dx:GridViewDataTextColumn>

第二种(不在本实体类中;在继承或者引用的实体类中;)

  1. <dx:GridViewDataHyperLinkColumn FieldName="Project.Oid" PropertiesHyperLinkEdit-TextField="ProjectName" Caption="项目">
  2. <EditFormSettings Visible="False" />
  3. <PropertiesHyperLinkEdit NavigateUrlFormatString="~/Projects/ViewAll.aspx?id={0}" ></PropertiesHyperLinkEdit>
  4. </dx:GridViewDataHyperLinkColumn>

其中 PropertiesHyperLinkEdit-TextField="ProjectName" 就相当于

  1. <PropertiesHyperLinkEdit TextField="ProjectName" >

9.GridView中每一列再对应一个GridView列表

  1. <dx:ASPxGridView ID="gvAll" runat="server" AutoGenerateColumns="False" DataSourceID="XpoMoudles" KeyFieldName="Oid" Width="100%" Caption="应用模块">
  2. <Columns>
  3. <dx:GridViewCommandColumn ShowEditButton="True" ShowDeleteButton="true" ShowNewButtonInHeader="True" VisibleIndex="0" Width="100px">
  4. </dx:GridViewCommandColumn>
  5. <dx:GridViewDataTextColumn FieldName="Name" VisibleIndex="1">
  6. </dx:GridViewDataTextColumn>
  7. <dx:GridViewDataTextColumn FieldName="Code" VisibleIndex="2">
  8. </dx:GridViewDataTextColumn>
  9. <dx:GridViewDataTextColumn FieldName="LastVersion" VisibleIndex="3">
  10. </dx:GridViewDataTextColumn>
  11. </Columns>
  12. <Templates>
  13. <DetailRow>
  14. <dx:ASPxPageControl ID="ASPxPageControl1" runat="server">
  15. <TabPages>
  16. <dx:TabPage Text="应用模板">
  17. <ContentCollection>
  18. <dx:ContentControl runat="server">
  19. <dx:ASPxGridView ID="gvdr" ClientInstanceName="gvdr" runat="server" AutoGenerateColumns="False" DataSourceID="XpoTemplete" KeyFieldName="Oid"
  20. OnBeforePerformDataSelect="gvdr_BeforePerformDataSelect" OnRowInserting="gvdr_RowInserting" >
  21. <Columns>
  22. <dx:GridViewCommandColumn ShowDeleteButton="True" ShowEditButton="True" ShowNewButtonInHeader="True" VisibleIndex="0" Width="100px">
  23. </dx:GridViewCommandColumn>
  24. <dx:GridViewDataTextColumn FieldName="Name" VisibleIndex="2">
  25. </dx:GridViewDataTextColumn>
  26. <dx:GridViewDataTextColumn FieldName="Code" VisibleIndex="3">
  27. </dx:GridViewDataTextColumn>
  28. <dx:GridViewDataTextColumn FieldName="LastVersion" VisibleIndex="4">
  29. </dx:GridViewDataTextColumn>
  30. </Columns>
  31. <SettingsEditing Mode="EditForm"></SettingsEditing>
  32. <SettingsBehavior ConfirmDelete="True" />
  33. </dx:ASPxGridView>
  34. </dx:ContentControl>
  35. </ContentCollection>
  36. </dx:TabPage>
  37. </TabPages>
  38. </dx:ASPxPageControl>
  39. </DetailRow>
  40. </Templates>
  41. <SettingsDetail ShowDetailRow="true" AllowOnlyOneMasterRowExpanded="true" />
  42. <SettingsBehavior AllowSelectSingleRowOnly="true" />
  43. <%-- <Settings HorizontalScrollBarMode="Visible" />--%>
  44. </dx:ASPxGridView>
  45. //后台代码
  46. protected void gvdr_BeforePerformDataSelect(object sender, EventArgs e)
  47. {
  48. var p = (sender as ASPxGridView).GetMasterRowKeyValue();
  49. if (p != null)
  50. Session["PS"] = p.ToString();
  51. else
  52. Session["PS"] = "-1";
  53. XpoTemplete.Criteria = CriteriaOperator.Parse("AppMoudless.Oid=?", Session["PS"].ToString()).ToString();
  54. }
  55. protected void gvdr_RowInserting(object sender, DevExpress.Web.Data.ASPxDataInsertingEventArgs e)
  56. {
  57. e.NewValues["AppMoudless!Key"] = int.Parse(Session["PS"].ToString());
  58. }

10.限制输入字数

  1. <dx:GridViewDataMemoColumn FieldName="ContentAbstract" Caption="研究内容提要" Visible="false">
  2. <PropertiesMemoEdit Rows="5" MaxLength="300" >
  3. <ValidationSettings>
  4. <RegularExpression ErrorText="最少100字" ValidationExpression=" ^(.|\n){0,300}$" />
  5. </ValidationSettings>
  6. </PropertiesMemoEdit>
  7. <EditFormSettings Visible="True" ColumnSpan="2" />
  8. </dx:GridViewDataMemoColumn>

只单行限制字数正则: ^.{100,300}$

多行限制计算字数: ^(.|\n){0,500}$

用控件自带的“MaxLength”属性控制最大值(多行)

11.导出Excle表格、Word文档、PDF格式

1/导出Excle表格

  1. <dx:ASPxGridViewExporter ID="gridExport" GridViewID="gvAll" runat="server">
  2. </dx:ASPxGridViewExporter>
  3. //后台代码
  4. protected void btnExcel_Click(object sender, EventArgs e)
  5. {
  6. gridExport.WriteXlsxToResponse("立项管理台帐" + DateTime.Now.ToString("yyyyMMdd"), new XlsxExportOptionsEx { ExportType = ExportType.WYSIWYG });
  7. }

2/Word文档

  1. <asp:Button Text="成果书WORD" runat="server" CssClass="btn btn-info" ID="btnCover" OnClick="btnCover_Click" />

后台

  1. private static object lk = new object();
  2. protected void btnCover_Click(object sender, EventArgs e)
  3. {
  4. Crack();// 破解Aspose.Words
  5. string newFile = ($"~/测量成果书{DateTime.Now.ToString("yyyyMMddHHmmssms")}{new Random().Next(99999)}.doc");
  6. Aspose.Words.Document doc = new Aspose.Words.Document(Server.MapPath("~/Measure/测量成果书.doc"));
  7. lock (lk)
  8. {
  9. docReplace(doc, "{Project.Name}", BindHelper.Bind(Remeasure, "Plan.Project.Name"));
  10. docReplace(doc, "{Code}", BindHelper.Bind(Remeasure, "Code"));
  11. docReplace(doc, "{Department.Name}", BindHelper.Bind(ScopeHelper.GetScope(Remeasure.Department), "Name"));
  12. docReplace(doc, "{bz}", BindHelper.Bind(Remeasure, "bz"));
  13. docReplace(doc, "{fh}", BindHelper.Bind(Remeasure, "fh"));
  14. docReplace(doc, "{sh}", BindHelper.Bind(Remeasure, "sh"));
  15. docReplace(doc, "{pz}", BindHelper.Bind(Remeasure, "pz"));
  16. docReplace(doc, "{date}", Remeasure?.UploadDate?.ToString("yyyy 年 M 月 d 日"));
  17. int ver = 'A';
  18. ver = ver + Remeasure.Approvals.Where(o => o.Result == ApprovalResult.Disagree).Count();
  19. docReplace(doc, "{ver}", Convert.ToChar(ver).ToString());
  20. string newPath = Server.MapPath(newFile);
  21. doc.Save(newPath);
  22. }
  23. Response.Redirect(newFile);
  24. }
  25. private static void Crack()//使用前调用一次即可
  26. {
  27. string[] stModule = new string[8]
  28. {
  29. "\u000E\u2008\u200A\u2001",
  30. "\u000F\u2008\u200A\u2001",
  31. "\u0002\u200A\u200A\u2001",
  32. "\u000F",
  33. "\u0006",
  34. "\u000E",
  35. "\u0003",
  36. "\u0002"
  37. };
  38. Assembly assembly = Assembly.GetAssembly(typeof(Aspose.Words.License));
  39. Type typeLic = null, typeIsTrial = null, typeHelper = null;
  40. foreach (Type type in assembly.GetTypes())
  41. {
  42. if ((typeLic == null) && (type.Name == stModule[0]))
  43. {
  44. typeLic = type;
  45. }
  46. else if ((typeIsTrial == null) && (type.Name == stModule[1]))
  47. {
  48. typeIsTrial = type;
  49. }
  50. else if ((typeHelper == null) && (type.Name == stModule[2]))
  51. {
  52. typeHelper = type;
  53. }
  54. }
  55. if (typeLic == null || typeIsTrial == null || typeHelper == null)
  56. {
  57. throw new Exception();
  58. }
  59. object lic = Activator.CreateInstance(typeLic);
  60. int findCount = 0;
  61. foreach (FieldInfo field in typeLic.GetFields(BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance))
  62. {
  63. if (field.FieldType == typeLic && field.Name == stModule[3])
  64. {
  65. field.SetValue(null, lic);
  66. ++findCount;
  67. }
  68. else if (field.FieldType == typeof(DateTime) && field.Name == stModule[4])
  69. {
  70. field.SetValue(lic, DateTime.MaxValue);
  71. ++findCount;
  72. }
  73. else if (field.FieldType == typeIsTrial && field.Name == stModule[5])
  74. {
  75. field.SetValue(lic, 1);
  76. ++findCount;
  77. }
  78. }
  79. foreach (FieldInfo field in typeHelper.GetFields(BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance))
  80. {
  81. if (field.FieldType == typeof(bool) && field.Name == stModule[6])
  82. {
  83. field.SetValue(null, false);
  84. ++findCount;
  85. }
  86. if (field.FieldType == typeof(int) && field.Name == stModule[7])
  87. {
  88. field.SetValue(null, 128);
  89. ++findCount;
  90. }
  91. }
  92. if (findCount < 5)
  93. {
  94. throw new NotSupportedException("无效的版本");
  95. }
  96. }
  97. private void docReplace(Aspose.Words.Document doc, string frindText, string replaceWith)
  98. {
  99. doc.Range.Replace(frindText, replaceWith, false, false);
  100. }

word文档格式:
文档:


                            {Project.Name}控制网 

                            测量成果书 


                            编号:{Code}
                            版本号:{ver}
                            编制:{bz}
                            复核:{fh}
                            审核:{sh}
                            批准:{pz}



                            中铁上海工程局集团有限公司 
                            {department.Name}编
                            {date}

3/pdf
右击打印保存pdf格式

12.输入框既可以下拉显示数据源数据 也可以手动输入

  1. <dx:GridViewDataComboBoxColumn FieldName="SupportProjectN" VisibleIndex="6" Caption="依托项目">
  2. <PropertiesComboBox DropDownStyle="DropDown">
  3. </PropertiesComboBox>
  4. </dx:GridViewDataComboBoxColumn>

DropDownStyle一定要是DropDown 不能是 DropDownlist

  1. protected void gvAll_OnCellEditorInitialize(object sender, ASPxGridViewEditorEventArgs e)
  2. {
  3. if (e.Column.FieldName == "SupportProjectN")
  4. {
  5. var cb = e.Editor as ASPxComboBox;
  6. if (cb == null)
  7. return;
  8. var project = new XPCollection<Project>(session, CriteriaOperator.Parse("StartsWith(Scope,?)", ScopeHelper.CurrentScope()));
  9. foreach (var item in project)
  10. {
  11. cb.Items.Add(item.Name,item.Name);
  12. }
  13. }
  14. }

13.保存的过程中,不满足条件,抛出异常,中断保存

if (Oid < 0)新建时候进去;编辑时不进入

  1. protected override void OnSaving()
  2. {
  3. base.OnSaving();
  4. if (Oid < 0)
  5. {
  6. Creator = Session.FindObject<CsUser>(CriteriaOperator.Parse("LoginName=?", HttpContext.Current.User.Identity.Name));
  7. Department = ScopeHelper.GetScope(Creator.Department);
  8. }
  9. if (AcceptTime != null)
  10. if (Photo1 == null)
  11. throw new Exception("未上传受理时间照片!");
  12. if (OAuthTime != null)
  13. if (Photo2 == null)
  14. throw new Exception("未上传授权时间照片!");
  15. }

14.在回调中打开网页

在新窗口打开

  1. url = "window.open('" + url + "')";
  2. ASPxWebControl.RedirectOnCallback("javascript:" + url);

在原窗口打开

  1. ASPxWebControl.RedirectOnCallback(url);

15.下拉多选框

  1. <script>
  2. function SelectAllGridLookup()
  3. {
  4. gdlp_dept.SelectAll();
  5. }
  6. </script>
  7. <dx:GridViewDataColumn FieldName="SupportProjectN" VisibleIndex="6" Caption="依托工程项目" Visible="false">
  8. <EditFormSettings Visible="True" />
  9. <EditItemTemplate>
  10. <dx:ASPxGridLookup ID="gdlp_dept" runat="server" SelectionMode="Multiple" ClientInstanceName="gdlp_dept" DataSourceID="XpoProject"
  11. KeyFieldName="Name" Width="200px" TextFormatString="{0}" MultiTextSeparator=", " GridViewStyles-Cell-Wrap="False" CssClass="f_l mr20" AutoGenerateColumns="False">
  12. <Columns>
  13. <dx:GridViewCommandColumn ShowSelectCheckbox="True" SelectAllCheckboxMode="Page" />
  14. <dx:GridViewDataColumn FieldName="Name" Settings-AllowAutoFilter="True" >
  15. </dx:GridViewDataColumn>
  16. </Columns>
  17. </dx:ASPxGridLookup>
  18. </EditItemTemplate>
  19. </dx:GridViewDataColumn>

数据绑定 参考实例2
记得同时设置一下控件的KeyFieldName属性为你要选中的值
item 就是前端的“Name” SetSelectionByKey 所有要KeyFieldName 也是Name,和选择的FieldName一致
这样在从数据库读出来编辑绑定时才有用

  1. protected void gvAll_HtmlDataCellPrepared(object sender, ASPxGridViewTableDataCellEventArgs e)
  2. {
  3. if ((gvAll.EditingRowVisibleIndex == e.VisibleIndex && e.DataColumn.FieldName == "SupportName") && !gvAll.IsNewRowEditing)
  4. {
  5. var cbl = gvAll.FindEditRowCellTemplateControl(gvAll.DataColumns["SupportProjectN"], "gdlp_dept") as ASPxGridLookup;
  6. var o = gvAll.GetRow(e.VisibleIndex) as PatentModel;
  7. var values = o?.SupportProjectN?.Split(',');
  8. if (values != null && values.Length > 0)
  9. {
  10. foreach (var item in values)
  11. {
  12. cbl.GridView.Selection.SetSelectionByKey(item, true);
  13. }
  14. }
  15. }
  16. }

16.身份证自动填生日、性别

  1. //身份证自动填生日、性别
  2. function IDNumberBlur(s, e) {
  3. var idNum = s.GetValue();
  4. if ($.isNumeric(idNum) && idNum.length == 18) {
  5. Birthday.SetValue(new Date(idNum.substring(6, 14).replace(/^(\d{4})(\d{2})(\d{2})$/, "$1-$2-$3")));
  6. if (idNum.substring(16, 17) % 2 == 0)
  7. Sex.SetValue("女");
  8. else
  9. Sex.SetValue("男");
  10. }
  11. }
  12. <dx:GridViewDataTextColumn FieldName="IDNumber" VisibleIndex="5" Visible="false">
  13. <PropertiesTextEdit MaxLength="18">
  14. <ValidationSettings ErrorText="身份证格式不对" >
  15. <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)" />
  16. <RequiredField IsRequired="True" ErrorText="不能为空"/>
  17. </ValidationSettings>
  18. </PropertiesTextEdit>
  19. <EditFormSettings Visible="True" />
  20. </dx:GridViewDataTextColumn>
  21. <dx:GridViewDataComboBoxColumn FieldName="Sex" VisibleIndex="6">
  22. <PropertiesComboBox ClientInstanceName="Sex">
  23. <Items>
  24. <dx:ListEditItem Value="男" />
  25. <dx:ListEditItem Value="女" />
  26. </Items>
  27. </PropertiesComboBox>
  28. </dx:GridViewDataComboBoxColumn>
  29. <dx:GridViewDataDateColumn FieldName="Birthday" VisibleIndex="7">
  30. <PropertiesDateEdit ClientInstanceName="Birthday"></PropertiesDateEdit>
  31. </dx:GridViewDataDateColumn>
  32. protected void gvAll_CellEditorInitialize(object sender, ASPxGridViewEditorEventArgs e)
  33. {
  34. //身份证自动填生日、性别
  35. if (e.Column.FieldName == "IDNumber")
  36. {
  37. e.Editor.SetClientSideEventHandler("LostFocus", "IDNumberBlur");
  38. }
  39. }

17.强制转换

C#中(int)、int.Parse()、int.TryParse()和Convert.ToInt32()的区别

  1. DateTime GraduationTime = Convert.ToDateTime(e.NewValues["GraduationTime"].ToString());
  2. int EducationOid = Convert.ToInt32(e.NewValues["Education!Key"].ToString());

18.表单编辑时添加图片按钮、上传文件按钮(回调函数中跳转页面)

//实体类

  1. [DisplayName("受理照片")]
  2. public string _Photo1;
  3. [DisplayName("授权照片")]
  4. public string _Photo2;
  5. [DisplayName("失效PDF"), Size(1000)]
  6. public string _Photo5;
  7. [DisplayName("备注PDF"), Size(1000)]
  8. public string _Photo6;
  9. [DisplayName("受理照片"), NonPersistent]
  10. public byte[] Photo1_1
  11. {
  12. set
  13. {
  14. var url = HttpContext.Current;
  15. if (value != null)
  16. {
  17. byte[] array = value;
  18. string path = url.Server.MapPath("~/Images/PhotoImage/" + PatentName + "-" + PatentNo + "受理" + ".jpg");
  19. FileStream fs = new FileStream(path, FileMode.Create);
  20. fs.Write(value, 0, value.Length);
  21. fs.Close(); ;
  22. _Photo1 = path;
  23. }
  24. else
  25. {
  26. try
  27. {
  28. string path = url.Server.MapPath("~/Images/PhotoImage/" + PatentName + "-" + PatentNo + "受理" + ".jpg");
  29. System.IO.File.Delete(path);
  30. _Photo1 = null;
  31. }
  32. catch { _Photo1 = null; }
  33. }
  34. }
  35. get { return null; }
  36. }
  37. [DisplayName("授权照片"), NonPersistent]
  38. public byte[] Photo2_2
  39. {
  40. set
  41. {
  42. var url = HttpContext.Current;
  43. if (value != null)
  44. {
  45. byte[] array = value;
  46. string path = url.Server.MapPath("~/Images/PhotoImage/" + PatentName + "-" + PatentNo + "授权" + ".jpg");
  47. FileStream fs = new FileStream(path, FileMode.Create);
  48. fs.Write(value, 0, value.Length);
  49. fs.Close();
  50. _Photo2 = path;
  51. }
  52. else
  53. {
  54. try
  55. {
  56. string path = url.Server.MapPath("~/Images/PhotoImage/" + PatentName + "-" + PatentNo + "授权" + ".jpg");
  57. System.IO.File.Delete(path);
  58. _Photo2 = null;
  59. }
  60. catch { _Photo2 = null; }
  61. }
  62. }
  63. get { return null; }
  64. }
  65. //[DisplayName("受理照片"), NonPersistent]
  66. //public byte[] Photo1
  67. //{
  68. // set
  69. // {
  70. // var url = HttpContext.Current;
  71. // if (value != null)
  72. // {
  73. // byte[] array = value;
  74. // string path = url.Server.MapPath("~/Images/PhotoImage/" + PatentName + "-" + PatentNo + "受理" + ".jpg");
  75. // FileStream fs = new FileStream(path, FileMode.Create);
  76. // fs.Write(value, 0, value.Length);
  77. // fs.Close(); ;
  78. // _Photo1 = path;
  79. // }
  80. // else
  81. // {
  82. // try
  83. // {
  84. // string path = url.Server.MapPath("~/Images/PhotoImage/" + PatentName + "-" + PatentNo + "受理" + ".jpg");
  85. // System.IO.File.Delete(path);
  86. // _Photo1 = null;
  87. // }
  88. // catch { _Photo1 = null; }
  89. // }
  90. // }
  91. // get
  92. // {
  93. // var url = HttpContext.Current;
  94. // try
  95. // {
  96. // string path = _Photo1;
  97. // FileStream fs = new FileStream(path, FileMode.Open);
  98. // long size = fs.Length;
  99. // byte[] array = new byte[size];
  100. // fs.Read(array, 0, array.Length);
  101. // fs.Close();
  102. // return array;
  103. // }
  104. // catch(Exception e)
  105. // { return null; }
  106. // }
  107. //}
  108. //[DisplayName("授权照片"), NonPersistent]
  109. //public byte[] Photo2
  110. //{
  111. // set
  112. // {
  113. // var url = HttpContext.Current;
  114. // if (value != null)
  115. // {
  116. // byte[] array = value;
  117. // string path = url.Server.MapPath("~/Images/PhotoImage/" + PatentName + "-" + PatentNo + "授权" + ".jpg");
  118. // FileStream fs = new FileStream(path, FileMode.Create);
  119. // fs.Write(value, 0, value.Length);
  120. // fs.Close();
  121. // _Photo2 = path;
  122. // }
  123. // else
  124. // {
  125. // try
  126. // {
  127. // string path = url.Server.MapPath("~/Images/PhotoImage/" + PatentName + "-" + PatentNo + "授权" + ".jpg");
  128. // System.IO.File.Delete(path);
  129. // _Photo2 = null;
  130. // }
  131. // catch { _Photo2 = null; }
  132. // }
  133. // }
  134. // get
  135. // {
  136. // var url = new System.Web.UI.Page();
  137. // try
  138. // {
  139. // string path = _Photo2;
  140. // FileStream fs = new FileStream(path, FileMode.Open);
  141. // long size = fs.Length;
  142. // byte[] array = new byte[size];
  143. // fs.Read(array, 0, array.Length);
  144. // fs.Close();
  145. // return array;
  146. // }
  147. // catch { return null; }
  148. // }
  149. //}
  150. [DisplayName("失效PDF"), NonPersistent]
  151. public string Photo3
  152. {
  153. set
  154. {
  155. var url = HttpContext.Current;
  156. if (value != null)
  157. {
  158. try
  159. {
  160. string date = DateTime.Now.ToString("yyyyMMddHHmmss");
  161. string path = url.Server.MapPath("~/Images/PhotoImage/" + PatentName + "-" + PatentNo + "PDF版专利证书扫描件"+ date+ ".pdf");
  162. //path = path
  163. System.IO.File.Move(value, path);
  164. _Photo5 = path;
  165. }
  166. catch (Exception e)
  167. {
  168. }
  169. }
  170. }
  171. get
  172. {
  173. return _Photo5;
  174. }
  175. }
  176. [DisplayName("备注PDF"), NonPersistent]
  177. public string Photo4
  178. {
  179. set
  180. {
  181. var url = HttpContext.Current;
  182. if (value != null)
  183. {
  184. try
  185. {
  186. string date = DateTime.Now.ToString("yyyyMMddHHmmss");
  187. string path = url.Server.MapPath("~/Images/PhotoImage/" + PatentName + "-" + PatentNo + "其他证明材料扫描件" + date + ".pdf");
  188. System.IO.File.Move(value, path);
  189. _Photo6 = path;
  190. }
  191. catch (Exception e)
  192. {
  193. }
  194. }
  195. }
  196. get
  197. {
  198. return _Photo6;
  199. }
  200. }

//照片控件

  1. <dx:GridViewDataBinaryImageColumn FieldName="Photo1_1" Visible="false" VisibleIndex="18" Caption="受理照片">
  2. <EditFormSettings Visible="True" />
  3. <PropertiesBinaryImage ImageHeight="100px" ImageWidth="90px">
  4. <ValidationSettings>
  5. <RequiredField IsRequired="true" ErrorText="不能为空" />
  6. </ValidationSettings>
  7. <EditingSettings Enabled="true" UploadSettings-UploadValidationSettings-MaxFileSize="2097152">
  8. <UploadSettings>
  9. <UploadValidationSettings MaxFileSize="2097152"></UploadValidationSettings>
  10. </UploadSettings>
  11. </EditingSettings>
  12. </PropertiesBinaryImage>
  13. </dx:GridViewDataBinaryImageColumn>
  14. <dx:GridViewDataBinaryImageColumn FieldName="Photo2_2" Visible="false" VisibleIndex="19" Caption="专利照片">
  15. <EditFormSettings Visible="True" />
  16. <PropertiesBinaryImage ImageHeight="100px" ImageWidth="90px">
  17. <EditingSettings Enabled="true" UploadSettings-UploadValidationSettings-MaxFileSize="2097152">
  18. <UploadSettings>
  19. <UploadValidationSettings MaxFileSize="2097152"></UploadValidationSettings>
  20. </UploadSettings>
  21. </EditingSettings>
  22. </PropertiesBinaryImage>
  23. </dx:GridViewDataBinaryImageColumn>

//实体类中注释Photo1、Photo2两张照片属性运行的话,会在初始化的时候就get图片;导致加载速度很慢,解决的方法就是在get的时候,不加载,在编辑单行数据的时候加载对应图片!所以重新写了Photo1_1和Photo2_2的属性,get的时候返回null,自定义编辑的时候获取图片代码如下:

  1. protected void gvAll_CellEditorInitialize(object sender, ASPxGridViewEditorEventArgs e)
  2. {
  3. if (e.Column.FieldName == "Photo1_1")
  4. {
  5. var url = HttpContext.Current;
  6. try
  7. {
  8. var m = session.FindObject<PatentModel>(CriteriaOperator.Parse("Oid=?", e.KeyValue.ToString()));
  9. string path = m._Photo1;
  10. FileStream fs = new FileStream(path, FileMode.Open);
  11. long size = fs.Length;
  12. byte[] array = new byte[size];
  13. fs.Read(array, 0, array.Length);
  14. fs.Close();
  15. e.Editor.Value = array;
  16. }
  17. catch
  18. { e.Editor.Value = null; }
  19. }
  20. if (e.Column.FieldName == "Photo2_2")
  21. {
  22. var url = HttpContext.Current;
  23. try
  24. {
  25. var m = session.FindObject<PatentModel>(CriteriaOperator.Parse("Oid=?", e.KeyValue.ToString()));
  26. string path = m._Photo2;
  27. FileStream fs = new FileStream(path, FileMode.Open);
  28. long size = fs.Length;
  29. byte[] array = new byte[size];
  30. fs.Read(array, 0, array.Length);
  31. fs.Close();
  32. e.Editor.Value = array;
  33. }
  34. catch
  35. { e.Editor.Value = null; }
  36. }
  37. }

//如果在按钮列自定义增加两个按钮,点击跳转对应的图片链接,则JS回调中获取不到自定义的名称组成的链接;只能在后台的回调中跳转,代码如下:

  1. //首先增加隐藏域(重点)
  2. <dx:ASPxHiddenField ID="HF" runat="server" ClientIDMode="Static"></dx:ASPxHiddenField>
  3. //控件:
  4. <dx:GridViewCommandColumn ShowDeleteButton="true" ShowNewButtonInHeader="true" ShowEditButton="true" Width="160px">
  5. <CustomButtons>
  6. <dx:GridViewCommandColumnCustomButton ID="btnView" Text="详情" ></dx:GridViewCommandColumnCustomButton>
  7. <%--<dx:GridViewCommandColumnCustomButton ID="btnSubmit" Text="提交"></dx:GridViewCommandColumnCustomButton>--%>
  8. <dx:GridViewCommandColumnCustomButton ID="btnphoto3" Text="受理照片" ></dx:GridViewCommandColumnCustomButton>
  9. <dx:GridViewCommandColumnCustomButton ID="btnphoto4" Text="授权照片"></dx:GridViewCommandColumnCustomButton>
  10. </CustomButtons>
  11. </dx:GridViewCommandColumn>
  12. //JS函数
  13. function gv_OnCustomButtonClick(s, e)
  14. {
  15. if (e.buttonID == "btnView")
  16. {
  17. window.open('View.aspx?id=' + s.GetRowKey(e.visibleIndex));
  18. }
  19. else if (e.buttonID == "btnSubmit")
  20. {
  21. if (confirm("确认提交通过此条信息?"))
  22. {
  23. s.PerformCallback(s.GetRowKey(e.visibleIndex));
  24. }
  25. }
  26. else if (e.buttonID == "btnphoto3")
  27. {
  28. //window.open('../Images/PhotoImage/' + e.text + "-" + e.text + "受理.jpg");
  29. //这种方法获取不到名称组成的链接
  30. HF.Set("Photo3Oid", s.GetRowKey(e.visibleIndex));
  31. gvAll.PerformCallback("Photo3View");
  32. }
  33. else if (e.buttonID == "btnphoto4")
  34. {
  35. HF.Set("Photo4Oid", s.GetRowKey(e.visibleIndex));
  36. gvAll.PerformCallback("Photo4View");
  37. }
  38. }
  39. //后台回调
  40. protected void gvAll_CustomCallback(object sender, ASPxGridViewCustomCallbackEventArgs e)
  41. {
  42. if (e.Parameters == "Go-1")
  43. {
  44. gvAll.PageIndex = -1;
  45. gvAll.DataBind();
  46. }
  47. else if (e.Parameters == "Photo3View")
  48. {
  49. var pat = session.FindObject<PatentModel>(CriteriaOperator.Parse("Oid=?", HF.Get("Photo3Oid")));
  50. //string url = "../Images/PhotoImage/" + pat.PatentName + " - " + pat.PatentNo + "受理.jpg";
  51. string url = TechManager.Module.Engine.PatentPhotoHelper.GetPhotoName(pat._Photo1);
  52. url = "window.open('" + url + "')";
  53. ASPxWebControl.RedirectOnCallback("javascript:"+url);
  54. }
  55. else if (e.Parameters == "Photo4View")
  56. {
  57. var pat = session.FindObject<PatentModel>(CriteriaOperator.Parse("Oid=?", HF.Get("Photo4Oid")));
  58. string url = TechManager.Module.Engine.PatentPhotoHelper.GetPhotoName(pat._Photo2);
  59. url = "window.open('" + url + "')";
  60. ASPxWebControl.RedirectOnCallback("javascript:" + url);
  61. }
  62. }
  63. //如果存在修改变更图片,因为图片保存的是byte格式;所以gvAll_RowUpdating函数中:
  64. m.Photo1_1 = (byte[])e.NewValues["Photo1_1"];
  65. m.Photo2_2 = (byte[])e.NewValues["Photo2_2"];

上传文件(PDF)控件

  1. //控件
  2. //AllowedFileExtensions=".pdf"控制了文件上传的格式
  3. <dx:GridViewDataColumn FieldName="Photo3" Visible="false" VisibleIndex="20" Caption="PDF版专利证书扫描件">
  4. <EditFormSettings Visible="True" />
  5. <EditItemTemplate>
  6. <dx:ASPxUploadControl ID="upload1" ClientInstanceName="upload1" runat="server" ShowUploadButton="True" UploadButton-Text="上传"
  7. UploadMode="Advanced" ShowProgressPanel="True" Width="280px" CssClass="f_l" Theme="Aqua" OnFileUploadComplete="upload1_FileUploadComplete">
  8. <ValidationSettings AllowedFileExtensions=".pdf"></ValidationSettings>
  9. <AdvancedModeSettings EnableFileList="True" EnableMultiSelect="False" EnableDragAndDrop="True" >
  10. </AdvancedModeSettings>
  11. <ClientSideEvents FileUploadComplete="onFileUploadComplete" />
  12. </dx:ASPxUploadControl>
  13. </EditItemTemplate>
  14. </dx:GridViewDataColumn>
  15. <dx:GridViewDataBinaryImageColumn FieldName="Photo4" Visible="false" VisibleIndex="21" Caption="其他证明材料扫描件">
  16. <EditFormSettings Visible="True" />
  17. <EditItemTemplate>
  18. <dx:ASPxUploadControl ID="upload2" ClientInstanceName="upload2" runat="server" ShowUploadButton="True" UploadButton-Text="上传"
  19. UploadMode="Advanced" ShowProgressPanel="True" Width="280px" CssClass="f_l" Theme="Aqua" OnFileUploadComplete="upload2_FileUploadComplete">
  20. -----------------------------------------------------------
  21. <ValidationSettings AllowedFileExtensions=".pdf"></ValidationSettings>
  22. <AdvancedModeSettings EnableFileList="True" EnableMultiSelect="False" EnableDragAndDrop="True" >
  23. </AdvancedModeSettings>
  24. <ClientSideEvents FileUploadComplete="onFileUploadComplete1" />
  25. --------------------------------------------------------------------------------
  26. </dx:ASPxUploadControl>
  27. </EditItemTemplate>
  28. </dx:GridViewDataBinaryImageColumn>
  29. //JS函数
  30. //onFileUploadComplete 相当于GridView中的CallBack
  31. function onFileUploadComplete(s, e) {
  32. if (e.callbackData) {
  33. HF.Set("Photo3", e.callbackData);
  34. }
  35. }
  36. function onFileUploadComplete1(s, e) {
  37. if (e.callbackData) {
  38. HF.Set("Photo4", e.callbackData);
  39. }
  40. }
  41. //后台函数
  42. // System.IO.File.Move是将上传的文件移动到临时文件夹并再加后缀名;因为存在的是临时文件,所以如果测试的时候文件上传成功了,在还没有保存之前就自动删除,则改变它的后缀名,如e.UploadedFile.FileNameInStorage + ".tt";改为.tt。e.CallbackData返回的是文件路径;
  43. protected void upload1_FileUploadComplete(object sender, FileUploadCompleteEventArgs e)
  44. {
  45. if (e.IsValid && !string.IsNullOrEmpty(e.UploadedFile.FileNameInStorage))
  46. {
  47. System.IO.File.Move(e.UploadedFile.FileNameInStorage, e.UploadedFile.FileNameInStorage+".pdf");
  48. e.CallbackData = e.UploadedFile.FileNameInStorage + ".pdf";
  49. }
  50. }
  51. protected void upload2_FileUploadComplete(object sender, FileUploadCompleteEventArgs e)
  52. {
  53. if (e.IsValid && !string.IsNullOrEmpty(e.UploadedFile.FileNameInStorage))
  54. {
  55. System.IO.File.Move(e.UploadedFile.FileNameInStorage, e.UploadedFile.FileNameInStorage + ".tt");
  56. e.CallbackData = e.UploadedFile.FileNameInStorage + ".tt";
  57. }
  58. }
  59. //这个时候文件还没有保存到我们希望的地方;还在临时文件夹里面,需要我们重新移动文件并重命名;所以在gvAll_RowInserting和gvAll_RowUpdating中都写下这样的代码;把临时路径给属性,在实体类中移动文件并重命名。
  60. if (HF.Contains("Photo3"))
  61. {
  62. m.Photo3 = HF.Get("Photo3").ToString();
  63. }
  64. if (HF.Contains("Photo4"))
  65. {
  66. m.Photo4 = HF.Get("Photo4").ToString();
  67. }

19.回调函数中跳转页面

  1. function gv_OnCustomButtonClick(s, e)
  2. {
  3. if (e.buttonID == "btnView")
  4. {
  5. window.open('View.aspx?id=' + s.GetRowKey(e.visibleIndex));
  6. }
  7. else if (e.buttonID == "btnSubmit")
  8. {
  9. if (confirm("确认提交通过此条信息?"))
  10. {
  11. s.PerformCallback(s.GetRowKey(e.visibleIndex));
  12. }
  13. }
  14. else if (e.buttonID == "btnphoto3")
  15. {
  16. //window.open('../Images/PhotoImage/' + e.text + "-" + e.text + "受理.jpg");
  17. HF.Set("Photo3Oid", s.GetRowKey(e.visibleIndex));
  18. gvAll.PerformCallback("Photo3View");
  19. }
  20. }
  21. protected void gvAll_CustomCallback(object sender, ASPxGridViewCustomCallbackEventArgs e)
  22. {
  23. if (e.Parameters == "Go-1")
  24. {
  25. gvAll.PageIndex = -1;
  26. gvAll.DataBind();
  27. }
  28. else if (e.Parameters == "Photo3View")
  29. {
  30. var pat = session.FindObject<PatentModel>(CriteriaOperator.Parse("Oid=?", HF.Get("Photo3Oid")));
  31. //string url = "../Images/PhotoImage/" + pat.PatentName + " - " + pat.PatentNo + "受理.jpg";
  32. string url = TechManager.Module.Engine.PatentPhotoHelper.GetPhotoName(pat._Photo1);
  33. url = "window.open('" + url + "')";
  34. ASPxWebControl.RedirectOnCallback("javascript:"+url);
  35. } else
  36. {
  37. //提交、、
  38. }

20.DevExpress GridView 不分页显示(全部显示)

  1. gv.SettingsPager.Mode = 0;

21.获取当前行的值;Oid

  1. var obj= (sender as ASPxGridView).GetRow(e.VisibleIndex) as InspectionMeasure;
  2. var masterKey = ((sender) as ASPxGridView).GetMasterRowKeyValue();
  3. var o = session.FindObject<EquipmentMeasure>(CriteriaOperator.Parse("Oid=?", masterKey));
  4. var InspectDate = gvAll.GetRowValues(e.VisibleIndex, "InspectDate");
  5. var eq = gvAll.GetRow(e.VisibleIndex) as EquipmentMeasure;

22.排序(按照关联表中某一属性排序)

  1. /// <summary>
  2. /// 人员表当中部门排序
  3. /// </summary>
  4. private static ArrayList CompanyArr;
  5. protected void gvAll_CustomColumnSort(object sender, DevExpress.Web.CustomColumnSortEventArgs e)
  6. {
  7. CompanyArr = CompanyArr ?? new ArrayList(new XPCollection<Department>(session, CriteriaOperator.Parse("1=1")
  8. , new SortProperty("Order", DevExpress.Xpo.DB.SortingDirection.Ascending) , new SortProperty("FullCode", DevExpress.Xpo.DB.SortingDirection.Ascending))
  9. .Select(o => o.Name).ToArray());
  10. CustomSortHelper.CustomFieldSort(e, "DepartmentCompany.Name|Department.Name", CompanyArr, CompanyArr);
  11. }

23.控件中获取子控件的方法

  1. var gvC = gvAll.FindControl("gv") as ASPxGridView;
  2. var v = (gvC.GetRow(gvC.EditingRowVisibleIndex) as TeamImplement)?.Project?.Oid;
  3. Repeater rep = e.Item.FindControl("rptList") as Repeater;//找到里层的repeater对象
  4. Detail rowv = (Detail)e.Item.DataItem;//找到分类Repeater关联的数据项
  5. //int typeid = Convert.ToInt32(rowv["Oid"]); //获取填充子类的id
  6. var list = new XPCollection<DetailList>(session, CriteriaOperator.Parse("Detail.Oid=?", rowv.Oid));
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注