转载请注明出处:http://surfsky.cnblogs.com/
---------------------------------------------------------
-- ASPxGridView 客户端API
---------------------------------------------------------
API
PerformCallback(this.value);
CollapseAll()
ExpandAll()
SelectRows()
UnselectRows()
UnselectAllRowsOnPage()
SelectAllRowsOnPage(this.checked)
---------------------------------------------------------
示例
---------------------------------------------------------
客户端事件按钮控制 grid 放缩
<input type="button" onclick="grid.CollapseAll();" value="Collapse All Rows" />
<input type="button" onclick="grid.ExpandAll();" value="Expand All Rows" />
<dxe:ASPxButton ID="btnUnselectAll" runat="server" Text="Unselect All" UseSubmitBehavior="False" AutoPostBack="false">
<ClientSideEvents Click="function(s, e) { grid.UnselectRows(); }"/>
</dxe:ASPxButton>
下拉框触发grid的ajax刷新
<select id="selGridLayout" onchange="grid.PerformCallback(this.value);" >
<option selected="selected" value="0">Country</option>
<option value="1">Country, City</option>
<option value="2">Company Name</option>
</select>
protected void grid_CustomCallback(object sender, ASPxGridViewCustomCallbackEventArgs e)
{
int layoutIndex = -1;
if(int.TryParse(e.Parameters, out layoutIndex))
ApplyLayout(layoutIndex);
}
用定时器出发grid的ajax刷新
<dxt:ASPxTimer ID="timer" ClientInstanceName="timer" runat="server" Interval="2000">
<ClientSideEvents Tick="function(s, e) {
timer.Stop();
grid.PerformCallback();
}" />
</dxt:ASPxTimer>
<ClientSideEvents EndCallback="function(s, e) {timer.Start();}" />
protected void grid_CustomCallback(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewCustomCallbackEventArgs e)
{
grid.DataBind();
}
---------------------------------------------
-- GridView 客户端选择行
---------------------------------------------
行聚焦(FocusedRowChanged)
注:必须定义行主键:gv.KeyFieldName = "UserId";
// 聚焦行变更事件。向服务器查询聚焦行的 "EmployeeID" 和 "Notes" 信息,并该信息将返回到 OnGetRowValues() 函数
function OnGridFocusedRowChanged() {
grid.GetRowValues(grid.GetFocusedRowIndex(), 'EmployeeID;Notes', OnGetRowValues);
}
// 处理服务器端传回的数据(values是个数组,包含 "EmployeeID" 和 "Notes" 值)
function OnGetRowValues(values) {
DetailImage.SetImageUrl("FocusedRow.aspx?Photo=" + values[0]);
DetailNotes.SetText(values[1]);
}
<dxwgv:ASPxGridView ID="grid" ClientInstanceName="grid" runat="server" DataSourceID="AccessDataSource1" KeyFieldName="EmployeeID"
PreviewFieldName="Notes" AutoGenerateColumns="False" EnableRowsCache="false" Width="100%">
<Columns>
<dxwgv:GridViewDataColumn FieldName="FirstName" VisibleIndex="0"/>
<dxwgv:GridViewDataColumn FieldName="Title" VisibleIndex="3"/>
<dxwgv:GridViewDataColumn FieldName="LastName" VisibleIndex="1"/>
<dxwgv:GridViewDataColumn FieldName="BirthDate" VisibleIndex="2"/>
<dxwgv:GridViewDataColumn FieldName="HireDate" VisibleIndex="4"/>
</Columns>
<Settings ShowGroupPanel="true" />
<SettingsBehavior AllowFocusedRow="True"/>
<ClientSideEvents FocusedRowChanged="function(s, e) { OnGridFocusedRowChanged(); }"/>
</dxwgv:ASPxGridView>
<p>详细信息:</p>
<dxe:ASPxImage runat="server" ID="DetailImage" ClientInstanceName="DetailImage" />
<dxe:ASPxMemo runat="server" ID="DetailNotes" ClientInstanceName="DetailNotes" Width="100%" Height="160" ReadOnly="true" />
用control键+点击行可多选
<SettingsBehavior AllowMultiSelection="true" />
全选、全部反选
<dxwgv:ASPxGridView ID="grid" ClientInstanceName="grid" runat="server" DataSourceID="AccessDataSource1" KeyFieldName="CustomerID" Width="100%">
<SettingsBehavior AllowGroup="false" AllowDragDrop="false" />
<Columns>
<dxwgv:GridViewCommandColumn ShowSelectCheckbox="True" VisibleIndex="0">
<HeaderTemplate>
<input type="checkbox" onclick="grid.SelectAllRowsOnPage(this.checked);" title="选择/放弃选择本页的所有行" />
</HeaderTemplate>
<HeaderStyle HorizontalAlign="Center" />
</dxwgv:GridViewCommandColumn>
<dxwgv:GridViewDataColumn FieldName="ContactName" VisibleIndex="1" />
<dxwgv:GridViewDataColumn FieldName="CompanyName" VisibleIndex="2" />
<dxwgv:GridViewDataColumn FieldName="City" VisibleIndex="3" />
<dxwgv:GridViewDataColumn FieldName="Region" VisibleIndex="4" />
<dxwgv:GridViewDataColumn FieldName="Country" VisibleIndex="5" />
</Columns>
</dxwgv:ASPxGridView>
客户端选择多行
<dxe:ASPxListBox ID="ASPxListBox1" ClientInstanceName="selList" runat="server" Height="250px" Width="120px" />
<p>
选择的记录条数:
<span id="selCount" style="font-weight: bold">0</span>
</p>
<dxwgv:ASPxGridView ID="grid" ClientInstanceName="grid" runat="server" DataSourceID="AccessDataSource1" KeyFieldName="CustomerID" Width="100%">
<Columns>
<dxwgv:GridViewCommandColumn ShowSelectCheckbox="True" VisibleIndex="0" />
<dxwgv:GridViewDataColumn FieldName="ContactName" VisibleIndex="1" />
<dxwgv:GridViewDataColumn FieldName="CompanyName" VisibleIndex="2" />
<dxwgv:GridViewDataColumn FieldName="City" VisibleIndex="3" />
<dxwgv:GridViewDataColumn FieldName="Region" VisibleIndex="4" />
<dxwgv:GridViewDataColumn FieldName="Country" VisibleIndex="5" />
</Columns>
<ClientSideEvents SelectionChanged="grid_SelectionChanged" />
</dxwgv:ASPxGridView>
----------------------------------------
function grid_SelectionChanged(s, e) {
s.GetSelectedFieldValues("ContactName", GetSelectedFieldValuesCallback);
}
function GetSelectedFieldValuesCallback(values) {
selList.BeginUpdate();
try {
selList.ClearItems();
for(var i = 0; i < values.length; i ++) {
selList.AddItem(values[i]);
}
} finally {
selList.EndUpdate();
}
document.getElementById("selCount").innerHTML = grid.GetSelectedRowCount();
}
客户端选择行
<script language="javascript" type="text/javascript">
//function is called on changing focused row
function OnGridFocusedRowChanged()
{
// Query the server for the "EmployeeID" and "Notes" fields from the focused row
// The values will be returned to the OnGetRowValues() function
grid.GetRowValues(grid.GetFocusedRowIndex(), 'EmployeeID;Notes', OnGetRowValues);
}
//Value array contains "EmployeeID" and "Notes" field values returned from the server
function OnGetRowValues(values)
{
var notes = document.getElementById("detailnotes");
notes.value = values[1];
var image = document.getElementById("detailimage");
image.src = "FocusedRow.aspx?Photo=" + values[0];
}
</script>
<dxwgv:ASPxGridView ID="grid" ClientInstanceName="grid" runat="server" DataSourceID="AccessDataSource1" KeyFieldName="EmployeeID" PreviewFieldName="Notes" AutoGenerateColumns="False" EnableRowsCache="false" Width="100%">
<Columns>
<dxwgv:GridViewDataColumn FieldName="FirstName" VisibleIndex="0"/>
<dxwgv:GridViewDataColumn FieldName="Title" VisibleIndex="3"/>
<dxwgv:GridViewDataColumn FieldName="LastName" VisibleIndex="1"/>
<dxwgv:GridViewDataColumn FieldName="BirthDate" VisibleIndex="2"/>
<dxwgv:GridViewDataColumn FieldName="HireDate" VisibleIndex="4"/>
</Columns>
<Settings ShowGroupPanel="true" />
<SettingsBehavior AllowFocusedRow="True"/>
<ClientSideEvents FocusedRowChanged="function(s, e) { OnGridFocusedRowChanged(); }"/>
</dxwgv:ASPxGridView>
<table cellpadding="5" cellspacing="2" style="width:100%">
<tr>
<td style="width:30%"><img id="detailimage" alt="Image" src=""/></td>
<td style="width:70%"><textarea id="detailnotes" style="padding:2px 4px 2px 4px;width:94%;vertical-align:top" readonly="readonly" rows="10" cols="50"></textarea></td>
</tr>
</table>
posted @ 2010-08-13 13:11 Kevin Cheng 阅读(791) 评论(0)
编辑
转载请注明出处:http://surfsky.cnblogs.com/
---------------------------------------------------------
-- ASPxGridView 模板
---------------------------------------------------------
ASPxGridView 提供以下几种自定义的模板视图
EditForm 编辑窗口。弹出式或附加在原记录下面
DetailRow 详细行。点击后以form方式查看记录的详细信息
PreviewRow 预览行。原记录下进行简短描述
DataRow 数据行视图。每一行的内容位置都是定制的。
注:列模板请参考文档《ASPxGridView.Column》
数据行模板(DataRow, 类似ListView 卡片视图)
<dxwgv:ASPxGridView ID="grid" ClientInstanceName="grid" runat="server" DataSourceID="AccessDataSource1" KeyFieldName="EmployeeID" Width="100%">
<Columns>
<dxwgv:GridViewDataColumn FieldName="FirstName" VisibleIndex="1" />
<dxwgv:GridViewDataColumn FieldName="Title" VisibleIndex="4" />
<dxwgv:GridViewDataColumn FieldName="Notes" Visible="False" />
<dxwgv:GridViewDataColumn FieldName="LastName" VisibleIndex="2" />
<dxwgv:GridViewDataColumn FieldName="BirthDate" VisibleIndex="3"/>
<dxwgv:GridViewDataColumn FieldName="HireDate" VisibleIndex="5"/>
</Columns>
<SettingsPager PageSize="5" />
<Templates>
<DataRow>
<div style="padding:5px">
<table class="templateTable" cellpadding="2" cellspacing="1" >
<tr>
<td rowspan="4"><img alt="" src="CardView.aspx?Photo=<%# Eval("EmployeeID")%>"/></td>
<td class="templateCaption">First Name</td>
<td><%# Eval("FirstName") %></td>
<td class="templateCaption">Last Name</td>
<td><%# Eval("LastName")%></td>
</tr>
<tr>
<td class="templateCaption">Title</td>
<td colspan="3"><%# Eval("Title")%></td>
</tr>
<tr>
<td class="templateCaption">Birth Date</td>
<td ><%# Eval("BirthDate")%></td>
<td class="templateCaption">Hire Date</td>
<td><%# Eval("HireDate")%></td>
</tr>
<tr>
<td colspan="4" style="white-space:normal"><%# Eval("Notes") %> </td>
</tr>
</table>
</div>
</DataRow>
</Templates>
</dxwgv:ASPxGridView>
编辑表单模板(EditForm)
示例一:两个标签页,一个用标准的编辑面板,一个展示memo字段
<Templates>
<EditForm>
<div style="padding:4px 4px 3px 4px">
<dxtc:ASPxPageControl runat="server" ID="pageControl" Width="100%">
<TabPages>
<dxtc:TabPage Text="Info" Visible="true">
<Controls>
<dxwgv:ASPxGridViewTemplateReplacement ID="Editors" ReplacementType="EditFormEditors" runat="server"></dxwgv:ASPxGridViewTemplateReplacement>
</Controls>
</dxtc:TabPage>
<dxtc:TabPage Text="Notes" Visible="true">
<Controls>
<dxe:ASPxMemo runat="server" ID="notesEditor" Text='<%# Eval("Notes")%>' Width="100%" Height="93px"></dxe:ASPxMemo>
</Controls>
</dxtc:TabPage>
</TabPages>
</dxtc:ASPxPageControl>
</div>
<div style="text-align:right; padding:2px 2px 2px 2px">
<dxwgv:ASPxGridViewTemplateReplacement ID="UpdateButton" ReplacementType="EditFormUpdateButton" runat="server"></dxwgv:ASPxGridViewTemplateReplacement>
<dxwgv:ASPxGridViewTemplateReplacement ID="CancelButton" ReplacementType="EditFormCancelButton" runat="server"></dxwgv:ASPxGridViewTemplateReplacement>
</div>
</EditForm>
</Templates>
protected string GetMemoText() {
ASPxPageControl pageControl = grid.FindEditFormTemplateControl("pageControl") as ASPxPageControl;
ASPxMemo memo = pageControl.FindControl("notesEditor") as ASPxMemo;
return memo.Text;
}
protected void grid_RowUpdating(object sender, DevExpress.Web.Data.ASPxDataUpdatingEventArgs e) {
e.NewValues["Notes"] = GetMemoText();
}
protected void grid_RowInserting(object sender, DevExpress.Web.Data.ASPxDataInsertingEventArgs e) {
e.NewValues["Notes"] = GetMemoText();
}
示例二
<Templates>
<EditForm>
<div style="padding:4px 4px 3px 4px">
<table>
<tr>
<% if(!grid.IsNewRowEditing) { %>
<td rowspan="4">
<div style="border: solid 1px #C2D4DA; padding: 2px;"><img alt="" src="TwoWayBinding.aspx?Photo=<%# Eval("EmployeeID")%>" /></div>
</td>
<% } %>
<td style="white-space:nowrap">First Name</td>
<td style="width:50%"><dxe:ASPxTextBox runat="server" ID="edFirst" Text='<%# Bind("FirstName") %>' Width="100%" /> </td>
<td style="white-space:nowrap">Last Name</td>
<td style="width:50%"><dxe:ASPxTextBox runat="server" ID="edLast" Text='<%# Bind("LastName") %>' Width="100%" /> </td>
</tr>
<tr>
<td>Title</td>
<td style="width:100%" colspan="3"><dxe:ASPxTextBox runat="server" ID="edTitle" Text='<%# Bind("Title") %>' Width="100%" /> </td>
</tr>
<tr>
<td style="white-space:nowrap">Birth Date</td>
<td style="width:50%"><dxe:ASPxDateEdit runat="server" ID="edBirth" Value='<%# Bind("BirthDate") %>' Width="100%" /> </td>
<td style="white-space:nowrap">Hire Date</td>
<td style="width:50%"><dxe:ASPxDateEdit runat="server" ID="edHire" Value='<%# Bind("HireDate") %>' Width="100%" /> </td>
</tr>
<tr>
<td colspan="4">
<dxe:ASPxMemo runat="server" ID="edNotes" Text='<%# Bind("Notes")%>' Width="100%" Height="100px" />
</td>
</tr>
</table>
</div>
<div style="text-align:right; padding:2px 2px 2px 2px">
<dxwgv:ASPxGridViewTemplateReplacement ID="UpdateButton" ReplacementType="EditFormUpdateButton" runat="server" />
<dxwgv:ASPxGridViewTemplateReplacement ID="CancelButton" ReplacementType="EditFormCancelButton" runat="server" />
</div>
</EditForm>
</Templates>
预览行模板(PreviewRow)
<Templates>
<PreviewRow>
<table style="border:none">
<tbody>
<tr>
<td style="width:25%;border:none;color:Black"><img alt="" src="Preview.aspx?Photo=<%# Eval("EmployeeID")%>"/></td>
<td style="border:none;"><%# Container.Text %></td>
</tr>
</tbody>
</table>
</PreviewRow>
</Templates>
细节行模板(DetailRow: 主从视图Master-Detail)
<dxe:ASPxCheckBox ID="chkSingleExpanded" runat="server" Text="Keep a single expanded row at a time" AutoPostBack="true" OnCheckedChanged="chkSingleExpanded_CheckedChanged" />
<dxwgv:ASPxGridView ID="grid" ClientInstanceName="grid" runat="server" DataSourceID="masterDataSource" KeyFieldName="CustomerID">
<Columns>
<dxwgv:GridViewDataColumn FieldName="ContactName" />
<dxwgv:GridViewDataColumn FieldName="CompanyName" />
<dxwgv:GridViewDataColumn FieldName="City" />
<dxwgv:GridViewDataColumn FieldName="Country" />
</Columns>
<Templates>
<DetailRow>
联系电话: <b><%# Eval("Phone")%></b>, 传真: <b><%# Eval("Fax")%></b><br/>
<dxwgv:ASPxGridView ID="detailGrid" runat="server" DataSourceID="detailDataSource" KeyFieldName="OrderID" Width="100%"
OnBeforePerformDataSelect="detailGrid_DataSelect" OnCustomUnboundColumnData="detailGrid_CustomUnboundColumnData">
<Settings ShowFooter="True" />
<SettingsDetail IsDetailGrid="true"/>
<Columns>
<dxwgv:GridViewDataColumn FieldName="OrderID" />
<dxwgv:GridViewDataColumn FieldName="OrderDate" />
<dxwgv:GridViewDataColumn FieldName="ShipName" />
<dxwgv:GridViewDataColumn FieldName="Quantity" Name="Quantity" />
<dxwgv:GridViewDataTextColumn FieldName="UnitPrice" >
<PropertiesTextEdit DisplayFormatString="c" />
</dxwgv:GridViewDataTextColumn>
<dxwgv:GridViewDataTextColumn FieldName="Total" UnboundType="Decimal">
<PropertiesTextEdit DisplayFormatString="c" />
</dxwgv:GridViewDataTextColumn>
</Columns>
<TotalSummary>
<dxwgv:ASPxSummaryItem FieldName="CompanyName" SummaryType="Count"/>
<dxwgv:ASPxSummaryItem FieldName="Total" SummaryType="Sum" DisplayFormat="c"/>
<dxwgv:ASPxSummaryItem FieldName="Quantity" SummaryType="Sum" />
</TotalSummary>
</dxwgv:ASPxGridView>
</DetailRow>
</Templates>
<SettingsDetail ShowDetailRow="true"/>
</dxwgv:ASPxGridView>
<asp:AccessDataSource ID="masterDataSource" runat="server" DataFile="~/App_Data/nwind.mdb"
SelectCommand="SELECT * FROM [Customers]">
</asp:AccessDataSource>
<asp:AccessDataSource ID="detailDataSource" runat="server" DataFile="~/App_Data/nwind.mdb"
SelectCommand="SELECT * FROM [Invoices] Where CustomerID = ?">
<SelectParameters>
<asp:SessionParameter Name="CustomerID" SessionField="CustomerID" Type="String" />
</SelectParameters>
</asp:AccessDataSource>
注意: detailGrid.SettingsDetail.IsDetailGrid = true 表明该grid是作为从表的数据表格用的
// 主表数据绑定
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
grid.DataBind();
grid.DetailRows.ExpandRow(0);
}
}
// 从表数据绑定
protected void gridDetail_DataBinding(object sender, EventArgs e)
{
ASPxGridView grid = sender as ASPxGridView;
if (grid != null)
{
int i = (int) grid.GetMasterRowKeyValue();
grid.DataSource = GetProducts(i);
}
}
// 从表数据选择?
protected void detailGrid_DataSelect(object sender, EventArgs e)
{
Session["CustomerID"] = (sender as ASPxGridView).GetMasterRowKeyValue();
}
// 从表定制列的展示
protected void detailGrid_CustomUnboundColumnData(object sender, ASPxGridViewColumnDataEventArgs e)
{
if(e.Column.FieldName == "Total")
{
decimal price = (decimal)e.GetListSourceFieldValue("UnitPrice");
int quantity = Convert.ToInt32(e.GetListSourceFieldValue("Quantity"));
e.Value = price * quantity;
}
}
// 控制从表的显隐
protected void chkSingleExpanded_CheckedChanged(object sender, EventArgs e)
{
grid.SettingsDetail.AllowOnlyOneMasterRowExpanded = chkSingleExpanded.Checked;
if(grid.SettingsDetail.AllowOnlyOneMasterRowExpanded)
{
grid.DetailRows.CollapseAllRows();
}
}
posted @ 2010-08-13 13:10 Kevin Cheng 阅读(813) 评论(1)
编辑
转载请注明出处:http://surfsky.cnblogs.com/
---------------------------------------------------------
-- ASPxGridView 事件
---------------------------------------------------------
ASPxGridView
默认是以callback方式(ajax方式)传递数据给服务器来实现局部刷新功能的
若要改为postback方式,可设置 EnableCallBacks = "false"
---------------------------------------------------------
展示视图
---------------------------------------------------------
RowCreated(创建行数据时触发,类似 GridView 的 DataItemCreate 事件)
protected void grid_HtmlRowCreated(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewTableRowEventArgs e)
{
if(e.RowType != DevExpress.Web.ASPxGridView.GridViewRowType.Data) return;
// 设置模板列lable控件值
Label label = grid.FindRowCellTemplateControl(e.VisibleIndex, null, "changePercent") as Label;
decimal change = (decimal)grid.GetRowValues(e.VisibleIndex, "Change");
label.Text = string.Format("{0:p}", change);
// 设置模板列image控件的图像
System.Web.UI.WebControls.Image img = (System.Web.UI.WebControls.Image)grid.FindRowCellTemplateControl(e.VisibleIndex, null, "changeImage");
img.Visible = false;
if(change != 0) {
img.Visible = true;
img.ImageUrl = change < 0 ? "~/Images/arRed.gif" : "~/Images/arGreen.gif";
label.ForeColor = change < 0 ? Color.Red : Color.Green;
}
}
HtmlRowPrepared(行准备?可在此设置行的展示效果,如背景)
protected void grid_HtmlRowPrepared(object sender, ASPxGridViewTableRowEventArgs e)
{
bool hasError = e.GetValue("FirstName").ToString().Length <= 1;
hasError = hasError || e.GetValue("LastName").ToString().Length <= 1;
hasError = hasError || !e.GetValue("Email").ToString().Contains("@");
hasError = hasError || (int)e.GetValue("Age") < 18;
DateTime arrival = (DateTime)e.GetValue("ArrivalDate");
hasError = hasError || DateTime.Today.Year != arrival.Year || DateTime.Today.Month != arrival.Month;
if(hasError) {
e.Row.ForeColor = System.Drawing.Color.Red;
}
}
UnboundColumnData (非绑定列数据填充)
protected void grid_CustomUnboundColumnData(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewColumnDataEventArgs e)
{
if(e.Column.FieldName == "Total")
{
decimal price = (decimal)e.GetListSourceFieldValue("UnitPrice");
int quantity = Convert.ToInt32(e.GetListSourceFieldValue("Quantity"));
e.Value = price * quantity;
}
}
CustomColumnDisplayText(定制列文本展示)
protected void grid_CustomColumnDisplayText(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewColumnDisplayTextEventArgs e)
{
if(object.Equals(e.Column, grid.Columns["Size"]))
e.DisplayText = GetSizeDisplayText(e.Value);
}
SummaryDisplayText(合计行文本展示)
protected void grid_SummaryDisplayText(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewSummaryDisplayTextEventArgs e) {
if(e.Item.FieldName == "Size") {
e.Text = GetSizeDisplayText(e.Value);
}
}
HeaderFilterFillItems(自定义过滤器处理逻辑)
protected void grid_HeaderFilterFillItems(object sender, ASPxGridViewHeaderFilterEventArgs e)
{
if(object.Equals(e.Column, grid.Columns["Total"])) {
PrepareTotalFilterItems(e);
return;
}
if(object.Equals(e.Column, grid.Columns["Quantity"])) {
PrepareQuantityFilterItems(e);
return;
}
}
---------------------------------------------------------
回调处理
---------------------------------------------------------
CustomCallback(Ajax 回调处理)
<select id="selGridLayout" onchange="grid.PerformCallback(this.value);" >
<option selected="selected" value="0">Country</option>
<option value="1">Country, City</option>
<option value="2">Company Name</option>
</select>
protected void grid_CustomCallback(object sender, ASPxGridViewCustomCallbackEventArgs e)
{
int layoutIndex = -1;
if(int.TryParse(e.Parameters, out layoutIndex))
ApplyLayout(layoutIndex); // 更换布局
}
CustomButtonCallback(定制按钮的ajax回调处理)
protected void grid_CustomButtonCallback(object sender, ASPxGridViewCustomButtonCallbackEventArgs e)
{
if(e.ButtonID != "Copy") return;
copiedValues = new Hashtable();
foreach(string fieldName in copiedFields)
copiedValues[fieldName] = grid.GetRowValues(e.VisibleIndex, fieldName);
grid.AddNewRow();
}
---------------------------------------------------------
编辑视图
---------------------------------------------------------
InitNewRow(新建行的数据初始化处理)
protected void grid_InitNewRow(object sender, DevExpress.Web.Data.ASPxDataInitNewRowEventArgs e)
{
if(copiedValues == null) return;
foreach(string fieldName in copiedFields) {
e.NewValues[fieldName] = copiedValues[fieldName];
}
}
CellEditorInitialize(编辑器初始化)
protected void grid_CellEditorInitialize(object sender, ASPxGridViewEditorEventArgs e)
{
if(grid.IsEditing && !grid.IsNewRowEditing && e.Column.FieldName == "City")
{
string country = (string)grid.GetRowValuesByKeyValue(e.KeyValue, "Country");
ASPxComboBox combo = e.Editor as ASPxComboBox;
FillCityCombo(combo, country);
combo.Callback += new CallbackEventHandlerBase(cmbCity_OnCallback);
}
}
StartRowEditing(开始编辑)
protected void grid_StartRowEditing(object sender, DevExpress.Web.Data.ASPxStartRowEditingEventArgs e)
{
if(!grid.IsNewRowEditing) {
grid.DoRowValidation();
}
}
RowValidating (行数据验证)
protected void grid_RowValidating(object sender, DevExpress.Web.Data.ASPxDataValidationEventArgs e)
{
foreach(GridViewColumn column in grid.Columns) {
GridViewDataColumn dataColumn = column as GridViewDataColumn;
if(dataColumn == null) continue;
if(e.NewValues[dataColumn.FieldName] == null) {
e.Errors[dataColumn] = "Value can't be null.";
}
}
if(e.Errors.Count > 0) e.RowError = "Please, fill all fields.";
if(e.NewValues["FirstName"] != null && e.NewValues["FirstName"].ToString().Length < 2) {
AddError(e.Errors, grid.Columns["FirstName"], "First Name must be at least two characters long.");
}
if(e.NewValues["LastName"] != null && e.NewValues["LastName"].ToString().Length < 2) {
AddError(e.Errors, grid.Columns["LastName"], "Last Name must be at least two characters long.");
}
if(e.NewValues["Email"] != null && !e.NewValues["Email"].ToString().Contains("@")) {
AddError(e.Errors, grid.Columns["Email"], "Invalid e-mail.");
}
int age = 0;
int.TryParse(e.NewValues["Age"] == null ? string.Empty : e.NewValues["Age"].ToString(), out age);
if(age < 18) {
AddError(e.Errors, grid.Columns["Age"], "Age must be greater than or equal 18.");
}
DateTime arrival = DateTime.MinValue;
DateTime.TryParse(e.NewValues["ArrivalDate"] == null ? string.Empty : e.NewValues["ArrivalDate"].ToString(), out arrival);
if(DateTime.Today.Year != arrival.Year || DateTime.Today.Month != arrival.Month) {
AddError(e.Errors, grid.Columns["ArrivalDate"], "Arrival date is required and must belong to the current month.");
}
if(string.IsNullOrEmpty(e.RowError) && e.Errors.Count > 0) e.RowError = "Please, correct all errors.";
}
posted @ 2010-08-13 13:09 Kevin Cheng 阅读(1372) 评论(3)
编辑
转载请注明出处:http://surfsky.cnblogs.com/
---------------------------------------------------------
-- DataSource 支持的数据源
-- DataTable
-- IList
-- BindingList
-- XXXDataSource
---------------------------------------------------------
DataTable
grid.DataSource = dt;
grid.DataBind();
IList
int articleId = Convert.ToInt32(Request.QueryString["articleId"]);
IList<BlogArticleImage> images = BlogArticleImage.ListArticleImages(articleId);
this.gvImages.KeyFieldName = "ImageId";
this.gvImages.DataSource = images;
this.gvImages.DataBind();
BindingList
private void CreateQuotes()
{
BindingList<Quote> res = new BindingList<Quote>();
foreach(string name in names)
{
Quote q = new Quote(name);
q.Value = (decimal)GetRandom().Next(800, 2000) / (decimal)10;
res.Add(q);
}
Session["Quotes"] = res;
}
AccessDataSource
<asp:AccessDataSource ID="AccessDataSource1" runat="server" DataFile="~/App_Data/nwind.mdb"
SelectCommand="SELECT * FROM [Customers]"
DeleteCommand="DELETE FROM [Customers] WHERE [CustomerID] = ?"
InsertCommand="INSERT INTO [Customers] ([CustomerID], [CompanyName], [ContactName], [ContactTitle], [Address], [City], [Region], [PostalCode], [Country], [Phone], [Fax]) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
UpdateCommand="UPDATE [Customers] SET [CompanyName] = ?, [ContactName] = ?, [ContactTitle] = ?, [Address] = ?, [City] = ?, [Region] = ?, [PostalCode] = ?, [Country] = ?, [Phone] = ?, [Fax] = ? WHERE [CustomerID] = ?"
/>
<asp:AccessDataSource ID="AccessDataSource1" runat="server" DataFile="~/App_Data/nwind.mdb"
OnDeleting="AccessDataSource1_Modifying" OnInserting="AccessDataSource1_Modifying" OnUpdating="AccessDataSource1_Modifying"
SelectCommand="SELECT * FROM [Customers]" DeleteCommand="DELETE FROM [Customers] WHERE [CustomerID] = ?"
InsertCommand="INSERT INTO [Customers] ([CustomerID], [CompanyName], [ContactName], [ContactTitle], [Address], [City], [Region], [PostalCode], [Country], [Phone], [Fax]) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
UpdateCommand="UPDATE [Customers] SET [CompanyName] = ?, [ContactName] = ?, [City] = ?, [Region] = ?, [Country] = ? WHERE [CustomerID] = ?">
<DeleteParameters>
<asp:Parameter Name="CustomerID" Type="String" />
</DeleteParameters>
<UpdateParameters>
<asp:Parameter Name="CompanyName" Type="String" />
<asp:Parameter Name="ContactName" Type="String" />
<asp:Parameter Name="City" Type="String" />
<asp:Parameter Name="Region" Type="String" />
<asp:Parameter Name="Country" Type="String" />
</UpdateParameters>
</asp:AccessDataSource>
protected void AccessDataSource1_Modifying(object sender, SqlDataSourceCommandEventArgs e) {
DemoSettings.AssertNotReadOnly();
}
用代码实现
AccessDataSource ds = new AccessDataSource();
ds.DataFile = AccessDataSource1.DataFile;
ds.SelectCommand = "select Photo from [Employees] where employeeid=" + id;
DataView view = (DataView)ds.Select(DataSourceSelectArguments.Empty);
if(view.Count > 0) return view[0][0] as byte[];
return null;
ObjectDataSource
<asp:ObjectDataSource ID="ObjectDataSource1" runat="server"
TypeName="Quotes"
SelectMethod="LoadQuotes"
/>
<asp:ObjectDataSource ID="ObjectDataSource1" runat="server"
DataObjectTypeName="PersonRegistration"
TypeName="MyPersonProvider"
SelectMethod="GetList" UpdateMethod="Update" InsertMethod="Insert"
/>
<asp:objectDataSource id="ObjectDataSource1" runat="server"
typename="PersonManager"
selectMethod="SelectPersons"
deleteMethod="DeletePerson"
updateMethod="UpdatePerson"
insertMethod="InsertPerson" >
<insertParameters>
<asp:parameter name="Id" type="Int32" />
</insertParameters>
</asp:objectDataSource>
ObjectDataSource.Parameters
<SelectParameters>
<asp:SessionParameter Name="IGYSID" SessionField="ID" Type="Int32" />
<asp:SessionParameter DefaultValue="0" Name="ICGFS" SessionField="ICGFS" Type="Int32" />
</SelectParameters>
<UpdateParameters>
<asp:Parameter Name="IWZID" />
<asp:Parameter Name="IGYSID" />
<asp:Parameter Name="ICGMXID" />
<asp:Parameter Name="IGYSBJID" />
<asp:Parameter Name="NBJ" />
<asp:Parameter Name="CBZ" />
</UpdateParameters>
<UpdateParameters>
<asp:FormParameter FormField="makeid" Name="MakeID" Type="String" />
<asp:FormParameter FormField="name" Name="Name" Type="String" />
<asp:FormParameter FormField="id" Name="ID" Type="String" ConvertEmptyStringToNull="False" />
</UpdateParameters>
ObjectDataSource 使用的类
(以下代码整理并修改至《ASP.NET 2.0 Revealed》P71-P78)
(另外一个购物篮的例子,参考P138)
public class Person
{
private int id;
private string firstName;
private string lastName;
public int Id {...}
public string FirstName {...}
public string LastName {...}
public Person(int id, string firstName, string lastName)
{
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
}
}
public class PersonCollection : List<Person> {}
public class PersonManager
{
private const string personsKey = "persons";
public PersonCollection SelectPersons()
{
HttpContext context = HttpContext.Current;
if (context.Application[personKey] == null)
{
PersonCollection persons = new PersonCollection();
persons.Add(new Person(0, "Patrick", "Lorenz"));
persons.Add(new Person(0, "Patrick", "Lorenz"));
persons.Add(new Person(0, "Patrick", "Lorenz"));
persons.Add(new Person(0, "Patrick", "Lorenz"));
context.Application[personKey] = persons;
}
return context.Application[personKey] as PersonCollection;
}
public Person SelectPerson(int id)
{
foreach (Person p in SelectPersons())
if (p.Id == id)
return p;
return null;
}
public void DeletePerson(int id)
{
PersonCollection persons = (Application[personKey] as PersonCollections);
Person person = SelectPerson(id);
if (person != null)
persons.Remove(person);
}
public void InsertPerson(int id, string firstName, string lastName)
{
PersonCollection persons = (Application[personKey] as PersonCollections);
persons.Add(new Person(id, firstName, lastName));
}
public void UpdatePerson(int id, string firstName, string lastName)
{
Person person = SelectPerson(id);
if (person != null)
{
person.FirstName = firstName;
person.LastName = lastName;
}
}
}
posted @ 2010-08-13 13:08 Kevin Cheng 阅读(623) 评论(0)
编辑
转载请注明出处:http://surfsky.cnblogs.com/
---------------------------------------------------------
-- ASPxGridView 编辑
-- 注意:想让GridView支持修改功能,必须指定KeyFieldName
---------------------------------------------------------
展示编辑按钮列
<dxwgv:GridViewCommandColumn VisibleIndex="0">
<EditButton Visible="True" Text="修改" />
<DeleteButton Visible="true" Text="删除" />
<NewButton Visible="True" Text="新建" />
<CancelButton Visible="true" Text="取消" />
<UpdateButton Visible="true" Text="保存" />
<ClearFilterButton Visible="true" Text="取消过滤" />
</dxwgv:GridViewCommandColumn>
编辑视图下控件的外观设置
<dx:GridViewDataMemoColumn ... PropertiesMemoEdit-Rows="4" EditFormSettings-ColumnSpan="2" />
或者
<dxwgv:GridViewDataMemoColumn FieldName="Notes" Visible="False">
<EditFormSettings RowSpan="4" ColumnSpan="2" />
</dxwgv:GridViewDataMemoColumn>
其它
多行编辑请参考: http://www.devexpress.com/Support/Center/e/E158.aspx
编辑表单模板,请参考《ASPxGridView.Templates》
示例一: 绑定到IList并实现删除和修改
<dx:ASPxGridView runat="server" ID="gvImages" KeyFieldName="ImageId"
OnRowDeleting="gvImages_RowDeleting" OnRowUpdating="gvImages_RowUpdating"
>
<SettingsEditing Mode="Inline" />
<SettingsBehavior ConfirmDelete="true" />
<Columns>
<dx:GridViewDataColumn FieldName="ImageId" Caption="ID" Visible="false" />
<dx:GridViewDataImageColumn FieldName="ThumbnailUrl" Caption="缩略图" PropertiesImage-DescriptionUrlField="ImageId" />
<dx:GridViewDataTextColumn FieldName="Description" Caption="说明" />
<dx:GridViewDataTextColumn FieldName="Keywords" Caption="关键字" />
<dx:GridViewCommandColumn Caption="编辑" >
<EditButton Visible="True" Text="修改" />
<DeleteButton Visible="True" Text="删除" />
<CancelButton Text="取消" />
<UpdateButton Text="保存" />
</dx:GridViewCommandColumn>
</Columns>
</dx:ASPxGridView>
// 展示
public void ShowArticleImages()
{
int articleId = Convert.ToInt32(Request.QueryString["articleId"]);
IList<BlogArticleImage> images = BlogArticleImage.ListArticleImages(articleId);
this.gvImages.KeyFieldName = "ImageId";
this.gvImages.DataSource = images;
this.gvImages.DataBind();
}
// 更新
protected void gvImages_RowUpdating(object sender, DevExpress.Web.Data.ASPxDataUpdatingEventArgs e)
{
int id = Convert.ToInt32(e.Keys[0]);
string descript = Convert.ToString(e.NewValues["Description"]);
string keywords = Convert.ToString(e.NewValues["Keywords"]);
BlogArticleImage image = BlogArticleImage.Retrieve(id);
if (image != null)
{
image.Description = descript;
image.Keywords = keywords;
image.Persist();
}
e.Cancel = true;
gvImages.CancelEdit();
ShowArticleImages();
}
// 删除
protected void gvImages_RowDeleting(object sender, DevExpress.Web.Data.ASPxDataDeletingEventArgs e)
{
int id = Convert.ToInt32(e.Keys[0]);
BlogArticleImage image = BlogArticleImage.Retrieve(id);
if (image != null)
{
System.IO.File.Delete(Server.MapPath(image.ImageUrl));
System.IO.File.Delete(Server.MapPath(image.ThumbnailUrl));
image.Remove();
}
e.Cancel = true;
gvImages.CancelEdit();
ShowArticleImages();
}
示例二: 控件访问权限控制及CRUD操作
<dx:ASPxGridView runat="server" ID="gv" Caption="基础网" KeyFieldName="ID" Width="3000"
OnRowDeleting="gv_RowDeleting" OnRowUpdating="gv_RowUpdating" OnRowInserting="gv_RowInserting"
OnInitNewRow="grid_InitNewRow" onhtmlrowcreated="gv_HtmlRowCreated" OnCellEditorInitialize="grid_CellEditorInitialize"
>
<Columns>
<dx:GridViewCommandColumn Caption="编辑" Width="60" >
<EditButton Visible="True" Text="修改" />
<DeleteButton Visible="true" Text="删除" />
<NewButton Visible="True" Text="新建" />
<CancelButton Visible="true" Text="取消" />
<UpdateButton Visible="true" Text="保存" />
</dx:GridViewCommandColumn>
<dx:GridViewDataColumn FieldName="ID" Caption="ID"/>
<dx:GridViewDataColumn FieldName="CREATE_DT" Caption="创建时间"/>
<dx:GridViewDataColumn FieldName="CREATOR" Caption="创建人"/>
<dx:GridViewDataComboBoxColumn FieldName="UNIT" Caption="处理单位" >
<PropertiesComboBox EnableSynchronization="False" EnableIncrementalFiltering="True" DropDownStyle="DropDown" />
</dx:GridViewDataComboBoxColumn>
<dx:GridViewDataColumn FieldName="RESULT" Caption="处理结果" />
<dx:GridViewDataMemoColumn FieldName="ED_CMT" Caption="政企部核对结果" PropertiesMemoEdit-Rows="4" EditFormSettings-ColumnSpan="2" />
</Columns>
</dx:ASPxGridView>
// 普通状态下的命令按钮显隐
protected void gv_HtmlRowCreated(object sender, ASPxGridViewTableRowEventArgs e)
{
if (!gv.IsEditing && e.RowType == DevExpress.Web.ASPxGridView.GridViewRowType.Data)
{
bool isAdmin = Common.IsInRoles(new string[] { WZWF.DAL.Roles.Admin });
string unit = gv.GetRowValues(e.VisibleIndex, "UNIT").ToString();
bool isAuth = Common.IsInRoles(
unit,
WZWF.DAL.Roles.EnterpriseDepartment,
WZWF.DAL.Roles.MaintainDepartment
);
// 修改按钮
WebControl btnModify = e.Row.Cells[0].Controls[0] as WebControl;
btnModify.Visible = isAuth;
// 新建按钮
WebControl btnAddNew = e.Row.Cells[0].Controls[1] as WebControl;
btnAddNew.Visible = isAdmin;
// 删除按钮
WebControl btnDelete = e.Row.Cells[0].Controls[2] as WebControl;
btnDelete.Visible = isAdmin;
}
}
// 编辑状态下的控件访问权限控制
// 管理员:unit, result, md_cmt, ed_cmt
// 政企部:ed_cmt
// 网络维护部:result, md_cmt
protected void grid_CellEditorInitialize(object sender, ASPxGridViewEditorEventArgs e)
{
if (gv.IsEditing)
{
// 受理单位下拉框
if (e.Column.FieldName == "UNIT")
{
ASPxComboBox combo = e.Editor as ASPxComboBox;
using (DbClean db = new DbClean())
{
combo.DataSource = db.ListUnits();
combo.TextField = "ROLE";
combo.ValueField = "ROLE";
combo.DataBind();
}
}
// 新建状态除了id以外都可以编辑
if (gv.IsNewRowEditing)
{
e.Editor.ReadOnly = (e.Column.FieldName == "ID");
}
// 修改状态下根据角色可编辑部分数据
else
{
e.Editor.ReadOnly = true;
if (e.Column.FieldName == "UNIT")
e.Editor.ReadOnly = !Common.IsInRoles(WZWF.DAL.Roles.Admin);
else if (e.Column.FieldName == "RESULT" || e.Column.FieldName == "MD_CMT")
e.Editor.ReadOnly = !Common.IsInRoles(WZWF.DAL.Roles.Admin, WZWF.DAL.Roles.MaintainDepartment);
else if (e.Column.FieldName == "ED_CMT")
e.Editor.ReadOnly = !Common.IsInRoles(WZWF.DAL.Roles.Admin, WZWF.DAL.Roles.EnterpriseDepartment);
}
}
// 可编辑控件设置背景色
e.Editor.BackColor = e.Editor.ReadOnly ? Color.White : Color.LightYellow;
}
// 删除
protected void gv_RowDeleting(object sender, ASPxDataDeletingEventArgs e)
{
int id = Convert.ToInt32(e.Keys[0]);
using (DbClean db = new DbClean())
db.DelBasicNet(id);
e.Cancel = true;
gv.CancelEdit();
ShowData(ViewState["Unit"].ToString());
}
// 更新
protected void gv_RowUpdating(object sender, ASPxDataUpdatingEventArgs e)
{
string unit = Convert.ToString(e.NewValues["UNIT"]);
string result = Convert.ToString(e.NewValues["RESULT"]);
string edCmt = Convert.ToString(e.NewValues["ED_CMT"]);
if (gv.IsEditing)
{
int id = Convert.ToInt32(e.Keys[0]);
using (DbClean db = new DbClean())
db.ModBasicNet(id, ...);
}
e.Cancel = true;
gv.CancelEdit();
ShowData(ViewState["Unit"].ToString());
}
// 新增
protected void grid_InitNewRow(object sender, ASPxDataInitNewRowEventArgs e)
{
e.NewValues["CREATOR"] = Page.User.Identity.Name;
e.NewValues["CREATE_DT"] = System.DateTime.Now;
}
protected void gv_RowInserting(object sender, ASPxDataInsertingEventArgs e)
{
string unit = Convert.ToString(e.NewValues["UNIT"]);
string result = Convert.ToString(e.NewValues["RESULT"]);
string edCmt = Convert.ToString(e.NewValues["ED_CMT"]);
if (gv.IsNewRowEditing)
{
using (DbClean db = new DbClean())
db.AddBasicNet(.....);
}
e.Cancel = true;
gv.CancelEdit();
ShowData(ViewState["Unit"].ToString());
}
posted @ 2010-08-13 13:07 Kevin Cheng 阅读(1063) 评论(0)
编辑
转载请注明出处:http://surfsky.cnblogs.com/
---------------------------------------------------------
-- ASPxGridView 列
---------------------------------------------------------
基本列(GridViewDataColumn)
<dxwgv:GridViewDataColumn FieldName="Country" VisibleIndex="5" />
其他列
<dx:GridViewDataTextColumn /> : 文本列
<dx:GridViewDataMemoColumn /> : 长文本列
<dx:GridViewDataImageColumn /> : 图像列
<dx:GridViewDataBinaryImageColumn /> : 二进制图像列
<dx:GridViewDataDateColumn /> : 日期列
<dx:GridViewDataTimeEditColumn /> : 时间列
<dx:GridViewDataComboBoxColumn /> : 组合框列
<dx:GridViewDataDropDownEditColumn /> : 下拉框编辑列?
<dx:GridViewCommandColumn /> : 命令按钮列
<dx:GridViewDataButtonEditColumn /> : 编辑按钮列?
<dx:GridViewDataCheckColumn /> : 复选框列
<dx:GridViewDataColorEditColumn /> : 色彩列
<dx:GridViewDataHyperLinkColumn /> : 超链接列
<dx:GridViewDataProgressBarColumn /> : 进度条列
<dx:GridViewDataSpinEditColumn /> : SpinEdit列
长文本列(GridViewDataMemoColumn)
编辑时展现为多行文本框
<dx:GridViewDataMemoColumn FieldName="ED_CMT" Caption="政企部核对结果"
EditCellStyle-BackColor="Yellow"
PropertiesMemoEdit-Rows="4"
EditFormSettings-ColumnSpan="2"
/>
超链接列(GridViewDataHyperLinkColumn)
<dx:GridViewDataHyperLinkColumn FieldName="ArticleId" Caption="查看" >
<PropertiesHyperLinkEdit Text="查看" TextFormatString="" />
</dx:GridViewDataHyperLinkColumn>
组合框列(GridViewDataComboBoxColumn)
<dx:ASPxGridView OnCellEditorInitialize="grid_CellEditorInitialize">
<dxwgv:GridViewDataComboBoxColumn FieldName="City" VisibleIndex="2">
<PropertiesComboBox EnableSynchronization="False" EnableIncrementalFiltering="True" DropDownStyle="DropDown" />
</dxwgv:GridViewDataComboBoxColumn>
</dx:ASPxGridView>
protected void grid_CellEditorInitialize(object sender, ASPxGridViewEditorEventArgs e)
{
// 用下拉框展示国家下的所有城市
if(grid.IsEditing && e.Column.FieldName != "City" && !grid.IsNewRowEditing)
{
ASPxComboBox combo = e.Editor as ASPxComboBox;
string country = (string)grid.GetRowValuesByKeyValue(e.KeyValue, "Country");
FillCityCombo(combo, country);
}
}
命令按钮列(GridViewCommandColumn)
标准按钮
<dx:ASPxGridView runat="server" KeyFieldName="ID"
OnRowDeleting="gv_RowDeleting" OnRowUpdating="gv_RowUpdating" OnRowInserting="gv_RowInserting"
<Columns>
<dxwgv:GridViewCommandColumn>
<EditButton Visible="True" Text="修改" />
<DeleteButton Visible="true" Text="删除" />
<NewButton Visible="True" Text="新建" />
<CancelButton Visible="true" Text="取消" />
<UpdateButton Visible="true" Text="保存" />
<ClearFilterButton Visible="true" Text="取消过滤" />
</dxwgv:GridViewCommandColumn>
</Columns>
</dx:ASPxGridView>
代码详见《ASPxGridView.DataBind》
复选框列
<dxwgv:GridViewCommandColumn ShowSelectCheckbox="True"/>
<dxwgv:GridViewCommandColumn ShowSelectCheckbox="True">
<HeaderTemplate>
<input type="checkbox" onclick="grid.SelectAllRowsOnPage(this.checked);" title="选择/放弃选择本页的所有行" />
</HeaderTemplate>
<HeaderStyle HorizontalAlign="Center" />
</dxwgv:GridViewCommandColumn>
自定义按钮
“删除”按钮
<dx:GridViewCommandColumn Caption="删除">
<CustomButtons>
<dx:GridViewCommandColumnCustomButton ID="DeleteFile" Text="删除" />
</CustomButtons>
</dx:GridViewCommandColumn>
protected void gv_CustomButtonCallback(object sender, ASPxGridViewCustomButtonCallbackEventArgs e)
{
if (e.ButtonID == "DeleteFile")
{
long fileId = Convert.ToInt64(gv.GetRowValues(e.VisibleIndex, "FileId"));
string fileName = gv.GetRowValues(e.VisibleIndex, "FileName").ToString();
string filePath = Common.Config.Path.PhysicalUploadFolder + gv.GetRowValues(e.VisibleIndex, "FilePath").ToString();
System.IO.File.Delete(filePath);
using (DbFile db = new DbFile())
db.DelFile(fileId);
ShowData(this.FileBatchId);
}
}
“复制行”按钮
<dx:ASPxGridView runat="server" OnCustomButtonCallback="grid_CustomButtonCallback">
<Columns>
<dxwgv:GridViewCommandColumn VisibleIndex="0">
<CustomButtons>
<dxwgv:GridViewCommandColumnCustomButton Text="复制行" ID="Copy" />
</CustomButtons>
</dxwgv:GridViewCommandColumn>
</Columns>
</dx:ASPxGridView>
Hashtable copiedValues;
protected void grid_CustomButtonCallback(object sender, ASPxGridViewCustomButtonCallbackEventArgs e)
{
if(e.ButtonID == "Copy")
{
copiedValues = new Hashtable();
foreach(string fieldName in copiedFields)
copiedValues[fieldName] = grid.GetRowValues(e.VisibleIndex, fieldName);
grid.AddNewRow();
}
}
protected void grid_InitNewRow(object sender, DevExpress.Web.Data.ASPxDataInitNewRowEventArgs e)
{
if(copiedValues != null)
foreach(string fieldName in copiedFields)
e.NewValues[fieldName] = copiedValues[fieldName];
}
非绑定列(GridViewDataTextColumn)
<dxwgv:GridViewDataTextColumn FieldName="Total" UnboundType="Decimal" />
protected void grid_CustomUnboundColumnData(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewColumnDataEventArgs e)
{
// Total = UnitPrice * Quantity
if(e.Column.FieldName == "Total")
{
decimal price = (decimal)e.GetListSourceFieldValue("UnitPrice");
int quantity = Convert.ToInt32(e.GetListSourceFieldValue("Quantity"));
e.Value = price * quantity;
}
}
模板列(GridViewDataTextColumn)
onhtmlrowcreated="grid_HtmlRowCreated"
<dxwgv:GridViewDataTextColumn Name="Percent" Caption="Change" FieldName="Change">
<DataItemTemplate>
<asp:Image ID="changeImage" runat="server" ImageUrl="~/Images/arGreen.gif" Visible="false" GenerateEmptyAlternateText="True" />
<asp:Label ID="changePercent" runat="server" Text="" />
<a href="javascript:void(0);" onclick="OnMoreInfoClick(this, '<%# Container.KeyValue %>')">更多...</a>
<a href="../pages/download.ashx?path=../uploads/<%#Eval("FilePath")%>&name=<%#Eval("FileName") %> " >下载</a>
</DataItemTemplate>
</dxwgv:GridViewDataTextColumn>
protected void grid_HtmlRowCreated(object sender, ASPxGridViewTableRowEventArgs e)
{
if (!grid.IsEditing && e.RowType == DevExpress.Web.ASPxGridView.GridViewRowType.Data)
{
// 操作 Label 控件
Label label = grid.FindRowCellTemplateControl(e.VisibleIndex, null, "changePercent") as Label;
decimal change = (decimal)grid.GetRowValues(e.VisibleIndex, "Change");
label.Text = string.Format("{0:p}", change);
// 操作 Image 控件
System.Web.UI.WebControls.Image img = (System.Web.UI.WebControls.Image)grid.FindRowCellTemplateControl(e.VisibleIndex, null, "changeImage");
img.Visible = false;
if(change != 0)
{
img.Visible = true;
img.ImageUrl = change < 0 ? "~/Images/arRed.gif" : "~/Images/arGreen.gif";
label.ForeColor = change < 0 ? Color.Red : Color.Green;
}
}
}
注:模板列中的事件如何写?手工写事件,如btn.OnClick += ...;
注:视图模板请参考文档《ASPxGridView.Templates》
------------------------------------------
-- 定制窗口
------------------------------------------
定制窗口(CustomizationWindow)
说明:一个小窗口,展示隐藏的列,可供用户选择,拖动到表格中就会显示,反之则隐藏
展示定制窗口(隐藏列为Region)
<dxwgv:ASPxGridView ID="grid" ClientInstanceName="grid" runat="server" KeyFieldName="CustomerID" >
<Columns>
<dxwgv:GridViewDataColumn FieldName="ContactName" />
<dxwgv:GridViewDataColumn FieldName="CompanyName" />
<dxwgv:GridViewDataColumn FieldName="City" />
<dxwgv:GridViewDataColumn FieldName="Region" Visible="false" />
<dxwgv:GridViewDataColumn FieldName="Country" />
</Columns>
<SettingsCustomizationWindow Enabled="True" />
<ClientSideEvents CustomizationWindowCloseUp="grid_CustomizationWindowCloseUp" />
</dxwgv:ASPxGridView>
在客户端控制显隐定制窗口
function button1_Click(s, e) {
if(grid.IsCustomizationWindowVisible())
grid.HideCustomizationWindow();
else
grid.ShowCustomizationWindow();
UpdateButtonText();
}
function grid_CustomizationWindowCloseUp(s, e) {
UpdateButtonText();
}
function UpdateButtonText() {
var text = grid.IsCustomizationWindowVisible() ? "Hide" : "Show";
text += " Customization Window";
button1.SetText(text);
}
相关的 Client API:
ShowCustomizationWindow()
HideCustomizationWindow()
IsCustomizationWindowVisible()
posted @ 2010-08-13 13:06 Kevin Cheng 阅读(1301) 评论(0)
编辑
转载请注明出处:http://surfsky.cnblogs.com/
前言
说实话,对于这种控件类的使用,我并不喜欢使用或者编写教程之类的文章,一来本来就很简单,二来实在没有这种时间。就我的经验而言,控件类学习最快的入门方式就是边看官方示例,边整理编程文档,此后基本上就可以脱离示例,看文档就可以编程了。此系列文档是ASPxGridView的编程有效参考,前前后后整理了很多回了,给有需要的人使用:)
---------------------------------------------------------
-- ASPxGridView 概述
---------------------------------------------------------

功能概述
·DevExpress 公司提供的优秀的 aspnet 网格控件
·丰富的内置样式
·内建的 Ajax 操作
·提供客户端 API
·内置的排序,分页,分组,过滤功能,无需另外编码
·支持多种现场编辑模式: inline, EditForm, EditFormAndDisplayRow, PopupEditForm
·可定制模板,支持卡片视图、主从表视图
资源
官方主页: http://www.devexpress.com/
论坛:
简单示例
(注意:FieldName 是区分大小写的)
<dxwgv:ASPxGridView ID="grid" runat="server" Width="100%">
<Columns>
<dxwgv:GridViewDataColumn FieldName="ContactName" />
<dxwgv:GridViewDataColumn FieldName="CompanyName" />
<dxwgv:GridViewDataColumn FieldName="City" />
<dxwgv:GridViewDataColumn FieldName="Region" />
<dxwgv:GridViewDataColumn FieldName="Country" />
</Columns>
</dxwgv:ASPxGridView>
grid.DataSource = dt;
grid.DataBind();
小贴士
(1)在web.config里面做配置
<pages>
<controls>
...
<add tagPrefix="dx" namespace="DevExpress.Web.ASPxEditors" assembly="DevExpress.Web.ASPxEditors.v9.3, Version=9.3.4.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a"/>
<add tagPrefix="dx" namespace="DevExpress.Web.ASPxHtmlEditor" assembly="DevExpress.Web.ASPxHtmlEditor.v9.3, Version=9.3.4.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a"/>
<add tagPrefix="dx" namespace="DevExpress.Web.ASPxGridView" assembly="DevExpress.Web.ASPxGridView.v9.3, Version=9.3.4.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a"/>
<add tagPrefix="dx" namespace="DevExpress.Web.ASPxGridView.Export" assembly="DevExpress.Web.v9.3, Version=9.3.4.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a"/>
<add tagPrefix="dx" namespace="DevExpress.Web.ASPxPanel" assembly="DevExpress.Web.v9.3, Version=9.3.4.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a"/>
<add tagPrefix="dx" namespace="DevExpress.Web.ASPxDataView" assembly="DevExpress.Web.v9.3, Version=9.3.4.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a"/>
<add tagPrefix="dx" namespace="DevExpress.Web.ASPxMenu" assembly="DevExpress.Web.v9.3, Version=9.3.4.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a"/>
<add tagPrefix="dx" namespace="DevExpress.Web.ASPxPanel" assembly="DevExpress.Web.v9.3, Version=9.3.4.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a"/>
<add tagPrefix="dx" namespace="DevExpress.Web.ASPxRoundPanel" assembly="DevExpress.Web.v9.3, Version=9.3.4.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a"/>
<add tagPrefix="dx" namespace="DevExpress.Web.ASPxCallbackPanel" assembly="DevExpress.Web.v9.3, Version=9.3.4.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a"/>
<add tagPrefix="dx" namespace="DevExpress.Web.ASPxUploadControl" assembly="DevExpress.Web.v9.3, Version=9.3.4.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a"/>
<add tagPrefix="dx" namespace="DevExpress.Web.ASPxRatingControl" assembly="DevExpress.Web.v9.3, Version=9.3.4.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a"/>
<add tagPrefix="dx" namespace="DevExpress.Web.ASPxObjectContainer" assembly="DevExpress.Web.v9.3, Version=9.3.4.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a"/>
<add tagPrefix="dx" namespace="DevExpress.Web.ASPxTabControl" assembly="DevExpress.Web.v9.3, Version=9.3.4.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a"/>
<add tagPrefix="dx" namespace="DevExpress.Web.ASPxClasses" assembly="DevExpress.Web.v9.3, Version=9.3.4.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a"/>
</controls>
</pages>
DevExpress 的web控件都处于不同的命名空间,使用起来很不方便。
经过这样处理后,统一了DevExpress web 控件的标签前缀,方便多了,如:
<dx:ASPxGridView runat="server" ...>
<dx:ASPxPageControl runat="server" ...>
<dx:ASPxMenu runat="server" ...>
(2)在CS 文件加上这几个using,有效减少页面代码
using DevExpress.Web.Data;
using DevExpress.Web.ASPxEditors;
using DevExpress.Web.ASPxGridView;
(3)常用的主题设置
<dx:ASPxGridView runat="server" >
<Styles CssFilePath="~/App_Themes/Glass/{0}/styles.css" CssPostfix="Glass">
<AlternatingRow Enabled="True" />
<Header ImageSpacing="5px" SortingImageSpacing="5px" >
<BackgroundImage ImageUrl="~/app_themes/glass/web/mItemHBack.gif" />
</Header>
</Styles>
<Images ImageFolder="~/App_Themes/Glass/{0}/">
<CollapsedButton Height="12px" Width="11px" />
<DetailCollapsedButton Height="9px" Width="9px" />
<PopupEditFormWindowClose Height="17px" Width="17px" />
</Images>
<Settings ShowFilterBar="Auto" />
<SettingsBehavior ConfirmDelete="true" AllowFocusedRow="True" />
<SettingsEditing
Mode="PopupEditForm"
PopupEditFormModal="true"
PopupEditFormHorizontalAlign="WindowCenter"
PopupEditFormVerticalAlign="WindowCenter"
PopupEditFormAllowResize="true"
/>
<SettingsText
EmptyDataRow="无数据"
PopupEditFormCaption="编辑"
ConfirmDelete="确定删除?"
/>
<SettingsPager PageSize="30" >
<Summary AllPagesText="页: {0} / {1} ({2}行)" />
</SettingsPager>
</dx:ASPxGridView>
(4)ASPxGridView 的属性设置方式比较独特
既可以传统的层层嵌套,如:
<dx:GridViewDataMemoColumn>
<EditFormSettings ColumnSpan="2" />
<PropertiesMemoEdit Rows="4" />
</dx:GridViewDataMemoColumn>
也可以简化为“组合属性名”(姑且这样称呼吧)的方式:
<dx:GridViewDataMemoColumn PropertiesMemoEdit-Rows="4" EditFormSettings-ColumnSpan="2" />
好处是可以一行摆平,坏处是这些组合属性名的名称很长很长很长...
说实话,个人认为
ASPxGridView 属性设计得还是蛮严谨的,其属性层层嵌套,含义明确。
(而另外一个类似的产品,Infragistic公司的UltraGrid 属性设计则是完全失控了)
如果是winform倒无所谓,全部在cs代码中设置了,但作为aspnet控件的话写出来的层次就会很冗长
故我考虑这是devexpress公司为aspnet控件设计出来的一种折衷方案,允许以组合属性的方式来设置。
实际使用情况呢,有时候我觉得很方便,有时候觉得还是很冗长,看情况用吧。
几个常用属性
IsEditing : 是否处于编辑状态
IsNewRowEditing : 是否是新建行的编辑状态
几个常用方法
获取单元格的值
decimal change = (decimal)grid.GetRowValues(e.VisibleIndex, "Change");
获取模板中的控件
Label label = grid.FindRowCellTemplateControl(e.VisibleIndex, null, "changePercent") as Label;
---------------------------------------------------------
-- 设置(settings)
---------------------------------------------------------
概述设置(Settings)
<Settings
GridLines="Vertical" : 网格样式 Vertical, Both, None
ShowGroupPanel="True" : 分组面板
ShowFooter="True" : 脚注面板
ShowFilterRow="True" : 过滤器行
ShowHeaderFilterButton="true" : 表头过滤按钮
ShowGroupFooter="VisibleAlways" : 分组脚注面板 Hidden | VisibleIfExpand | VisibleAlways
ShowPreview="true" : 预览面板
ShowVerticalScrollBar="True" : 垂直滚动条
VerticalScrollableHeight="250" : 垂直滚动条
/>
行为设置(SettingsBehavior)
<SettingsBehavior
AllowDragDrop="False" : 允许托拽
ColumnResizeMode="Control" : 列宽度调整模式
AllowFocusedRow="True" : 鼠标点击选择行
/>
分页(SettingsPager)
<SettingsPager
PageSize="30" : 分页大小
Mode="ShowAllRecords" : 展示模式
SEOFriendly="Enabled" : Search engine friendly
Position="TopAndBottom" : 分页控件位置
>
<Summary AllPagesText="页: {0} / {1} ({2}行)" />
</SettingsPager>
文本设置(SettingsText)
<SettingsText
Title="标题"
EmptyDataRow="无数据"
PopupEditFormCaption="编辑"
ConfirmDelete="确定删除?"
/>
Loading 面板设置(SettingsLoadingPanel)
<SettingsLoadingPanel Mode="ShowOnStatusBar" />
编辑视图设置(SettingsEditing)
<SettingsEditing
PopupEditFormWidth = "600px"
NewItemRowPosition = "Bottom"
Mode = "PopupEditForm"
/>
编辑模式 SettingsEditing.Mode
EditForm : 当前行转化为表单,嵌入在行中
EditFormAndDisplayRow : 同EditForm,但保留当前行
Inline : 在当前行现场编辑
PopupEditForm : 弹出窗口编辑
---------------------------------------------------------
-- 样式 & 格式
---------------------------------------------------------
集中式样式
<Styles>
<Header HorizontalAlign="Center" /> : 标题居中对齐
<AlternatingRow Enabled="true"/> : 交错行效果
<CommandColumn Paddings-Padding="1" /> :
</Styles>
列样式
<dxwgv:GridViewDataTextColumn FieldName="Total" UnboundType="Decimal">
<FooterCellStyle ForeColor="Brown"/>
</dxwgv:GridViewDataTextColumn>
数字日期格式
金额
<dxwgv:GridViewDataTextColumn FieldName="UnitPrice" >
<PropertiesTextEdit DisplayFormatString="c" />
</dxwgv:GridViewDataTextColumn>
时间
<dxwgv:GridViewDataDateColumn Caption="Time" FieldName="Time">
<PropertiesDateEdit DisplayFormatString="HH:mm:ss" />
<CellStyle HorizontalAlign="Right" />
</dxwgv:GridViewDataDateColumn>
图像
<Images ImageFolder="~/App_Themes/Glass/{0}/">
<CollapsedButton Height="12px" Width="11px" />
<DetailCollapsedButton Height="9px" Width="9px" />
<PopupEditFormWindowClose Height="17px" Width="17px" />
</Images>
---------------------------------------------------------
-- 分组 & 汇总 & 排序
---------------------------------------------------------
间隔分组:将时间日期字段按个性分组,如年、月、日、周、季度、上周、下周.....
<dxwgv:GridViewDataDateColumn FieldName="OrderDate" VisibleIndex="3" GroupIndex="0">
<Settings GroupInterval="DateYear"/>
</dxwgv:GridViewDataDateColumn>
汇总
<TotalSummary>
<dxwgv:ASPxSummaryItem FieldName="CompanyName" SummaryType="Count"/>
<dxwgv:ASPxSummaryItem FieldName="Total" SummaryType="Sum" DisplayFormat="c"/>
<dxwgv:ASPxSummaryItem FieldName="Quantity" SummaryType="Min" />
<dxwgv:ASPxSummaryItem FieldName="Quantity" SummaryType="Average" />
<dxwgv:ASPxSummaryItem FieldName="Quantity" SummaryType="Max" />
</TotalSummary>
分组汇总
<GroupSummary>
<dxwgv:ASPxSummaryItem FieldName="Country" SummaryType="Count" />
<dxwgv:ASPxSummaryItem FieldName="Quantity" SummaryType="Sum" />
<dxwgv:ASPxSummaryItem FieldName="Total" SummaryType="Sum" DisplayFormat="{0:c}"/>
</GroupSummary>
---------------------------------------------------------
-- 杂
---------------------------------------------------------
排序
默认就是支持点击标题排序的,不过注意Page_Load中不能用 IsPostBack,如:
protected void Page_Load(object sender, EventArgs e)
{
grid.DataSource = ....;
grid.DataBind();
}
ASPxGridView 在每次请求来的时候先绑定,然后再根据排序或分页请求,过滤数据后展示给用户
当然,你也可以像 GridView 那样在服务器端自己写排序或者分页代码,麻烦就是了
指定列的排序顺序
<dxwgv:GridViewDataColumn FieldName="ContactName" SortOrder="Ascending" />
用代码指定排序列集合
grid.GroupSummarySortInfo.Clear();
DevExpress.Data.ColumnSortOrder sortOrder = DevExpress.Data.ColumnSortOrder.Ascending; //Descending
grid.GroupSummarySortInfo.AddRange(new ASPxGroupSummarySortInfo("Country", grid.GroupSummary["Total"], sortOrder));
导出文件
<dxwgv:ASPxGridViewExporter ID="gvExporter" runat="server" GridViewID="gv" />
this.gridExporter.WritePdfToResponse();
this.gridExporter.WriteXlsToResponse();
this.gridExporter.WriteRtfToResponse();
this.gridExporter.WriteCsvToResponse();
服务器端杂代码
grid.BeginUpdate();
grid.ClearSort();
grid.GroupBy((GridViewDataColumn)grid.Columns["Country"]);
grid.EndUpdate();
grid.ExpandAll();
grid.FindRowCellTemplateControl(e.VisibleIndex, null, "changePercent") as Label;
posted @ 2010-08-13 13:04 Kevin Cheng 阅读(1499) 评论(3)
编辑