在回发telerik:RadGrid后,Filter TextBox值消失

时间:2016-06-10 12:12:40

标签: c# asp.net vb.net telerik telerik-grid

我正在尝试按列过滤数据,但在回发后数据将从文本框中删除

<%@ Page Title="" Language="VB" MasterPageFile="~/MasterPage.master" AutoEventWireup="true"
    CodeFile="DynamicTestCaseReport.aspx.vb" Inherits="DynamicTestCaseReport" %>

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
    <link rel="shortcut icon" href="Images/TM32.ico" />
    <link href="css/style.css" rel="stylesheet" type="text/css" />
    <link href="css/TestMagic.css" rel="stylesheet" type="text/css" />
    <link href="css/calendar.css" rel="stylesheet" type="text/css" />
    <link href="css/calendar.css" rel="stylesheet" type="text/css" />
    <sript runat="server"></sript>

    <asp:ToolkitScriptManager ID="ToolScriptManager1" runat="server">
    </asp:ToolkitScriptManager>

    <table id="tblData" cellspacing="0" cellpadding="0" width="100%" border="0" runat="server">
        <tr>
            <td>
                <div id="rowlblError" runat="server" align="center">
                    <asp:Label ID="lblError" runat="server" CssClass="LabelMessage">
                    </asp:Label>
                </div>
            </td>
        </tr>
        <tr>
            <td align="center" class="Title">
                <asp:Label ID="lblDisplayHeader" runat="server"></asp:Label>
            </td>
        </tr>
        <tr>
            <td align="center">
                <asp:Label ID="lblMsg" runat="server" CssClass="LabelMessage"></asp:Label>
            </td>
        </tr>
        <tr>
            <td>

                <asp:Label ID="lblTemplate" runat="server" Text="Template Name : "></asp:Label>
                <asp:DropDownList ID="cboTemplate" runat="server" AutoPostBack="True" OnSelectedIndexChanged="cboTemplate_SelectedIndexChanged"
                    CssClass="text1" Width="200px">
                </asp:DropDownList>

            </td>

        </tr>
        <tr>
            <td style="padding-top: 10px;">
                <asp:CheckBoxList Width="100%" runat="server" ID="chkFields" DataTextField="Column_name"
                    DataValueField="Column_name" ToolTip="Please select data fields for report generation."
                    RepeatColumns="4" RepeatDirection="Horizontal" RepeatLayout="Table" BorderStyle="Solid"
                    TextAlign="Right" BorderWidth="1" BorderColor="Black" />
            </td>
        </tr>
        <tr>

            <td style="padding-top: 10px;">
                <table style="width: 990px;">
                    <tr>
                        <td>
                            <asp:Label ID="lblTemplateName" runat="server" Text="Enter Template Name : "></asp:Label>
                            <asp:TextBox ID="txtTemp" runat="server" MaxLength="100" Columns="22" Width="150"></asp:TextBox>
                            <asp:Button ID="btnSaveTemplate" runat="server" Text="Save Template" CssClass="BigBtn" />
                        </td>

                        <td align="right" style="padding-left: 200px;">

                            <asp:Button ID="btnShowGrid" runat="server" Text="Generate"
                                CssClass="NormalBtn" />
                            <asp:Button ID="btnCancel" runat="server" Text="Cancel"
                                CssClass="NormalBtn" />
                        </td>
                    </tr>
                </table>


            </td>

            <%--      <td align="left" style="padding-right: 200px;">
                <asp:Button ID="btnShowGrid" runat="server" Text="Generate"
                    CssClass="NormalBtn" />
                <asp:Button ID="btnCancel" runat="server" Text="Cancel"
                    CssClass="NormalBtn" />
            </td>--%>
        </tr>

        <tr>
            <td style="padding-top: 10px;">

                <div id="gridDiv" runat="server" style="z-index: 1; overflow: scroll;">

                    <telerik:RadGrid ID="gridData" runat="server" Visible="true" OnGridExporting="grid_GridExporting">
                    </telerik:RadGrid>

                </div>
            </td>
        </tr>
        <tr>
            <td align="right" style="padding-top: 10px;">
                <div id="gridDiv1" runat="server">
                    <asp:Button ID="btnEmailReport" runat="server" Text="Email Report"
                        CssClass="BigBtn" />
                    <asp:Button ID="btnExcel" runat="server" Text="Export to Excel"
                        CssClass="BigBtn" />
                   <asp:Button ID="btnECSV" runat="server" Text="Export to CSV"
                        CssClass="BigBtn" />
                      <asp:Button ID="btnEPDF" runat="server" Text="Export to PDF"
                        CssClass="BigBtn" />
                </div>
            </td>
        </tr>
    </table>
</asp:Content>

CS代码我做了必要的设置,如果没有,请纠正我:

    Partial Class DynamicTestCaseReport
    Inherits System.Web.UI.Page
    Dim objGeneral As TestMagic.General
    Protected Form1 As New System.Web.UI.HtmlControls.HtmlForm
    Dim flag As Boolean = False
    Dim flagcheck As Boolean = False
    Dim common As TestMagic.General = New TestMagic.General()
    Dim ServerPath As String = Server.MapPath("ReportViewer")

#Region " Web Form Designer Generated Code "

    'This call is required by the Web Form Designer.
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()

    End Sub
    Protected WithEvents lbldata As System.Web.UI.WebControls.Label

    Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
        'CODEGEN: This method call is required by the Web Form Designer
        'Do not modify it using the code editor.
        InitializeComponent()
    End Sub

#End Region


    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) ' Handles MyBase.Load
        'Put user code to initialize the page here
        ServerPath = common.ReadResourceFileaddress(ServerPath)
        If Not IsPostBack Then

            'Dim ServerPath As String = Server.MapPath("ReportViewer")


            Dim objAdmin As New Admin()
            Dim allCloumn As New DataSet
            allCloumn = objAdmin.GetAllColumsFromDB()
            FillTemplate()

            If allCloumn Is Nothing Then
                gridDiv.Visible = False
                gridDiv1.Visible = False
                btnShowGrid.Enabled = False
                btnCancel.Enabled = False
                lblError.Text = common.ReadResourceValue(ServerPath, "ReportrelatedTableisnotpresentinDataBase")
                Exit Sub
            End If

            chkFields.DataSource = allCloumn
            chkFields.DataBind()
            Session.Add("myDataGrid", gridData)
            'chkFields.Items(0).Enabled = False
            'chkFields.Items(0).Selected = True

            Dim intVal As Integer = chkFields.Items.Count
            'For a = 0 To intVal - 1
            '    chkFields.Items(a).Selected = True
            'Next  
            Session("DynamicResultReportGridData") = Nothing
        End If

        Dim ds As New DataSet
        ds = Session("DynamicResultReportGridData")
        If Not ds Is Nothing Then
            DefineGridStructure(Session("DynamicResultReportGridData"))
            gridData.DataBind()
            gridDiv.Visible = True
            gridDiv1.Visible = True
            btnShowGrid.Enabled = True
            btnCancel.Enabled = True
        Else
            gridDiv.Visible = False
            gridDiv1.Visible = False
            'btnShowGrid.Enabled = False
            'btnCancel.Enabled = False
            'lblError.Text = "Report related Table is not present in DataBase."
        End If



        lblDisplayHeader.Text = common.ReadResourceValue(ServerPath, "CustomizeTestCaseResultReport") 'common.ReadResourceValue(ServerPath, "TestCaseResultReport")

    End Sub


    Protected Sub btnShowGrid_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnShowGrid.Click

        Try
            Dim objAdmin As New Admin()
            Dim allCloumnData As New DataSet
            gridDiv.Visible = False
            gridDiv1.Visible = False
            allCloumnData = objAdmin.GetAllDataFromTestCaseResult()
            Dim intVal As Integer = chkFields.Items.Count
            If allCloumnData Is Nothing Then
                lblError.Text = common.ReadResourceValue(ServerPath, "ReportrelatedTableisnotpresentinDataBase") & common.ReadResourceValue(ServerPath, "PleaseAddColumnsfirst")
                Exit Sub
            Else
                lblError.Text = ""
            End If
            For a = intVal - 1 To 0 Step -1
                If Not chkFields.Items(a).Selected Then
                    allCloumnData.Tables(0).Columns.RemoveAt(a)
                End If
            Next

            If Not allCloumnData.Tables(0).Columns.Count > 0 Then
                lblError.Text = common.ReadResourceValue(ServerPath, "Pleaseselecttherequiredcolumnstogeneratethereport")
                Exit Sub
            Else
                lblError.Text = ""
            End If

            'INSERT Identity column
            Dim dc As New DataColumn("ID_Data")
            dc.AutoIncrement = True
            dc.AutoIncrementSeed = 1
            dc.AutoIncrementStep = 1
            allCloumnData.Tables(0).Columns.Add(dc)

            'Set values for existing rows
            For i As Integer = 0 To allCloumnData.Tables(0).Rows.Count - 1
                allCloumnData.Tables(0).Rows(i).Item("ID_Data") = i + 1
            Next


            gridDiv.Visible = True
            gridDiv1.Visible = True
            DefineGridStructure(allCloumnData)
            gridData.DataBind()

        Catch ex As Exception
            lblError.Text = "Error : " & ex.Message.ToString()
        End Try

    End Sub
    Protected Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancel.Click

        Response.Redirect(Request.RawUrl)
    End Sub




    Protected Sub btnEmailReport_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEmailReport.Click
        gridDiv.Visible = True
        gridData.Visible = True
        flag = True
        Dim data As New DataSet
        data = Session("DynamicResultReportGridData")
        DefineGridStructure(data)
        gridData.Rebind()

        gridData.ExportSettings.Excel.Format = GridExcelExportFormat.Biff
        gridData.ExportSettings.IgnorePaging = True
        gridData.ExportSettings.ExportOnlyData = False
        gridData.ExportSettings.OpenInNewWindow = True

        gridData.MasterTableView.ExportToExcel()

    End Sub


    Protected Sub grid_GridExporting(ByVal source As Object, ByVal e As GridExportingArgs)
        If flag Then
            'Dim filename As String = "TestCaseResultReport.xls"
            Dim strDateTime As String = Date.Now.ToString()
            strDateTime = strDateTime.Replace("/", "")
            strDateTime = strDateTime.Replace(" ", "_")
            strDateTime = strDateTime.Replace(":", "-")
            Dim filename As String = "TestCaseResultReport_" & strDateTime & ".xls"
            Dim path As String = Server.MapPath("~/PDFReport/") + filename
            Using fs As FileStream = File.Create(path)
                Dim info As [Byte]() = System.Text.Encoding.[Default].GetBytes(e.ExportOutput)
                fs.Write(info, 0, info.Length)
            End Using

            Response.Redirect("EmailReport.aspx?docID=" & filename & "&ids=dy")
        End If
    End Sub




    Private Function Company_Excel() As String
        Return ""
    End Function


    Protected Sub btnEPDF_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEPDF.Click
        'gridDiv.Visible = True
        'gridData.Visible = True

        Dim data As New DataSet
        data = Session("DynamicResultReportGridData")
        'DefineGridStructure(data)

        ''grid.ExportSettings.Pdf.AllowPrinting = True
        'gridData.ExportSettings.Pdf.PaperSize = GridPaperSize.Letter
        'gridData.ExportSettings.Pdf.PageWidth = 1500
        ''grid.ExportSettings.Pdf.PageTitle = "Users"
        ''grid.ExportSettings.Pdf.AllowModify = True
        ''grid.ExportSettings.Pdf.AllowCopy = True

        'gridData.ExportSettings.Pdf.FontType = Telerik.Web.Apoc.Render.Pdf.FontType.Embed

        'gridData.ExportSettings.IgnorePaging = True
        'gridData.ExportSettings.ExportOnlyData = False
        'gridData.ExportSettings.OpenInNewWindow = True

        'ApplyStyleSheetExportPDF(gridData.MasterTableView)
        'gridData.MasterTableView.ExportToPdf()

        Dim General As New TestMagic.General()
        Try
            Dim objDefectManagement_ExportToPDF As New DefectManagement_ExportToPDF()
            objDefectManagement_ExportToPDF.ProjectName = Convert.ToString(Session("Project"))
            'objDefectManagement_ExportToPDF.SubProjectName = Convert.ToString(Session("SubProject"))
            ' objDefectManagement_ExportToPDF.StartDate = Convert.ToDateTime(ViewState("StartDate")).ToString("MM/dd/yyyy")
            ' objDefectManagement_ExportToPDF.EndDate = Convert.ToDateTime(ViewState("EndDate")).ToString("MM/dd/yyyy")


            Dim pdfName As String = objDefectManagement_ExportToPDF.ExportToPDF_ManageDefects(True, data.Tables(0), "CustomizeTestCaseResultReport")
        Catch ex As Exception
            rowlblError.Visible = True
            lblError.Text = General.ReadResourceValue(ServerPath, "GeneralexceptionoccurredwhileretrievingPDFReport")
        End Try


    End Sub



    Protected Sub btnExcel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExcel.Click
        gridDiv.Visible = True
        gridData.Visible = True

        Dim data As New DataSet
        data = Session("DynamicResultReportGridData")
        DefineGridStructure(data)
        gridData.Rebind()
        gridData.ExportSettings.Excel.Format = GridExcelExportFormat.Biff

        gridData.ExportSettings.IgnorePaging = True
        gridData.ExportSettings.ExportOnlyData = False
        gridData.ExportSettings.OpenInNewWindow = True

        For Each item As GridNoRecordsItem In gridData.MasterTableView.GetItems(GridItemType.NoRecordsItem)
            item.Display = False
        Next

        gridData.MasterTableView.ExportToExcel()
    End Sub
    Protected Sub btnECSV_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnECSV.Click
        gridDiv.Visible = True
        gridData.Visible = True

        Dim data As New DataSet
        data = Session("DynamicResultReportGridData")
        DefineGridStructure(data)
        gridData.Rebind()
        gridData.ExportSettings.IgnorePaging = True
        gridData.ExportSettings.ExportOnlyData = False
        gridData.ExportSettings.OpenInNewWindow = True
        gridData.MasterTableView.ExportToCSV()
    End Sub

    Private Sub DefineGridStructure(ByVal allCloumnData As DataSet)

        'Dim grid As New RadGrid()

        gridData.DataSource = allCloumnData
        Session.Add("DynamicResultReportGridData", allCloumnData)
        gridData.Skin = "Default"
        gridData.Width = Unit.Percentage(100)
        gridData.PageSize = 15
        gridData.AllowPaging = True
        gridData.AllowFilteringByColumn = True
        gridData.PagerStyle.Mode = GridPagerMode.NextPrevAndNumeric
        gridData.AutoGenerateColumns = False

        'Add Customers table
        gridData.MasterTableView.Width = Unit.Percentage(100)

        If gridData.MasterTableView.Columns.Count > 0 Then
            For a = gridData.MasterTableView.Columns.Count - 1 To 0 Step -1
                gridData.MasterTableView.Columns.RemoveAt(a)
            Next

        End If

        gridData.MasterTableView.DataKeyNames = New String() {"ID_Data"}

        Dim intVal As Integer = allCloumnData.Tables(0).Columns.Count
        For a = 0 To intVal - 2
            Dim boundColumn As New GridBoundColumn()

            boundColumn.DataField = allCloumnData.Tables(0).Columns(a).Caption().Trim().ToString()
            boundColumn.HeaderText = allCloumnData.Tables(0).Columns(a).Caption().Trim().ToString()
            boundColumn.UniqueName = allCloumnData.Tables(0).Columns(a).Caption().Trim().ToString()
            boundColumn.ItemStyle.CssClass = "text2"

            boundColumn.HeaderStyle.CssClass = "GridHeader"
            boundColumn.AllowFiltering = True
            gridData.MasterTableView.Columns.Add(boundColumn)
        Next


    End Sub

    Protected Sub grid_NeedDataSource(ByVal Source As Object, ByVal e As Telerik.Web.UI.GridNeedDataSourceEventArgs) Handles gridData.NeedDataSource

        gridDiv.Visible = True
        gridDiv1.Visible = True
        gridData.Visible = True
        Dim allCloumnData As DataSet = Session("DynamicResultReportGridData")
        gridData.DataSource = allCloumnData

    End Sub

    'To Save Tempate Details
    Protected Sub btnSaveTemplate_Click(sender As Object, e As EventArgs) Handles btnSaveTemplate.Click
        Dim objAdmin As New TestMagic.Admin()
        Dim dsData As New DataSet
        Dim columnName As String = ""
        Dim result As Boolean
        Dim isTemplate As Boolean
        gridDiv.Visible = False
        gridDiv1.Visible = False


        Dim myArray As New ArrayList()
        For Each item As ListItem In chkFields.Items
            If item.Selected = True Then
                myArray.Add(item)
                columnName = String.Concat(columnName, "|", item.Value)
            End If
        Next

        If Trim(txtTemp.Text).Length = 0 Then 'check template name should not blank
            lblMsg.Text = common.ReadResourceValue(ServerPath, "Pleaseentertemplatename")

        ElseIf myArray.count = 0 Then 'check column name should not unchecked

            lblMsg.Text = common.ReadResourceValue(ServerPath, "Pleaseselectcolumnname")
        Else

            Try
                dsData = objAdmin.ShowColumns(cboTemplate.SelectedValue, HttpContext.Current.Session("Project"))

                If dsData.Tables(0).Rows.Count > 0 Then

                    'Update Template Details
                    result = objAdmin.UpdateTemplate(cboTemplate.SelectedValue, columnName, HttpContext.Current.Session("Project"))

                    If result Then
                        lblMsg.Text = common.ReadResourceValue(ServerPath, "Templateupdatedsuccessfully")
                    End If

                Else

                    'Check Template Name Already Exist or Not
                    isTemplate = objAdmin.IsTemplateExist(txtTemp.Text.Trim, HttpContext.Current.Session("Project"))

                    If isTemplate Then

                        lblMsg.Text = common.ReadResourceValue(ServerPath, "Thistemplatenameisalreadyexist")

                    Else
                        'Save Template Details
                        result = objAdmin.AddTemplate(txtTemp.Text.Trim, columnName, HttpContext.Current.Session("Project"))

                        If result Then
                            lblMsg.Text = common.ReadResourceValue(ServerPath, "Templatesavedsuccessfully")

                            FillTemplate()
                            cboTemplate.SelectedIndex = cboTemplate.Items.IndexOf(cboTemplate.Items.FindByText(txtTemp.Text.Trim))

                        End If

                    End If

                End If
            Catch ex As Exception

            End Try

        End If


    End Sub


    Private Sub FillTemplate()
        Dim objAdmin As New Admin()
        cboTemplate.Items.Clear()
        cboTemplate.DataSource = objAdmin.ShowTemplate(HttpContext.Current.Session("Project"))
        cboTemplate.DataTextField = "TemplateName"
        cboTemplate.DataValueField = "Id"
        cboTemplate.DataBind()
        cboTemplate.Items.Insert(0, New ListItem("<New Template>", 0))
        cboTemplate.SelectedIndex = 0
    End Sub

    Protected Sub cboTemplate_SelectedIndexChanged(sender As Object, e As EventArgs)
        Dim objAdmin As New TestMagic.Admin()
        Dim dsData As New DataSet
        Dim allCloumn As New DataSet
        gridDiv.Visible = False
        gridDiv1.Visible = False

        lblMsg.Text = " "

        'Get columns by Template & Project
        dsData = objAdmin.ShowColumns(cboTemplate.SelectedValue, HttpContext.Current.Session("Project"))

        For Each item As ListItem In chkFields.Items
            item.Selected = False
        Next

        If cboTemplate.SelectedValue <> 0 Then

            ViewState("columnsName") = dsData.Tables(0).Rows(0).Item("ColumnsName").ToString()

            Dim columnsName As String = ViewState("columnsName")
            Dim columns As String() = columnsName.Split("|")

            Dim column As String
            For Each column In columns
                For Each item As ListItem In chkFields.Items
                    If column = item.Value Then
                        item.Selected = True
                    End If
                Next
            Next


            'For Each item As ListItem In chkFields.Items
            '    If columnsName.Contains(item.Value) Then
            '        item.Selected = True
            '    End If
            'Next

            txtTemp.Text = cboTemplate.SelectedItem.Text
            txtTemp.Enabled = False

        Else

            txtTemp.Text = " "
            txtTemp.Enabled = True

            For Each item As ListItem In chkFields.Items
                item.Selected = False
            Next

        End If

    End Sub

End Class

在回发telerik:RadGrid后,滤镜TextBox值消失 提前谢谢。

2 个答案:

答案 0 :(得分:0)

在这里我发现我的代码中有一个问题,我的同事在isPostBack之外编写了gridData.DataBind()的代码,这是错误的,然后在下面的代码中出现错误。

gridData.MasterTableView.DataKeyNames = New String() {"ID_Data"}

        Dim intVal As Integer = allCloumnData.Tables(0).Columns.Count
        For a = 0 To intVal - 2
            Dim boundColumn As New GridBoundColumn()

            boundColumn.DataField = allCloumnData.Tables(0).Columns(a).Caption().Trim().ToString()
            boundColumn.HeaderText = allCloumnData.Tables(0).Columns(a).Caption().Trim().ToString()
            boundColumn.UniqueName = allCloumnData.Tables(0).Columns(a).Caption().Trim().ToString()
            boundColumn.ItemStyle.CssClass = "text2"

            boundColumn.HeaderStyle.CssClass = "GridHeader"
            boundColumn.AllowFiltering = True
            gridData.MasterTableView.Columns.Add(boundColumn)
        Next

然后我将代码更改为。

gridData.MasterTableView.DataKeyNames = New String() {"ID_Data"}

        Dim intVal As Integer = allCloumnData.Tables(0).Columns.Count
        For a = 0 To intVal - 2
            Dim boundColumn As New GridBoundColumn()

            gridData.MasterTableView.Columns.Add(boundColumn) 

            boundColumn.DataField = allCloumnData.Tables(0).Columns(a).Caption().Trim().ToString()
            boundColumn.HeaderText = allCloumnData.Tables(0).Columns(a).Caption().Trim().ToString()
            boundColumn.UniqueName = allCloumnData.Tables(0).Columns(a).Caption().Trim().ToString()
            boundColumn.ItemStyle.CssClass = "text2"
            boundColumn.HeaderStyle.CssClass = "GridHeader"
            boundColumn.AllowFiltering = True            
        Next

应首先添加列。现在更改代码我的fitbox TextBox保留了过滤后的值。

谢谢大家..

答案 1 :(得分:0)

RadGrid的异常行为可能有两个原因。

  1. 数据绑定

将数据绑定到RadGrid时,开发人员常犯的常见错误是结合使用通用DataBind()方法和Grid的NeedDataSource事件。这种“必须避免”的情况在Most common mistake developers make when bindingHow to bind RadGrid properly on server-side

中有描述

Telerik组件主要是通用ASP控件的包装,而这些组件继承了大多数ASP控件的属性和方法,包括DataBind()方法。

曾经使用GridView和其他ASP控件的开发人员,他们习惯于绑定数据的经典方式,使用RadGrid时遵循相同的原理。但是,RadGrid是GridView的扩展版本,它具有自己的和推荐的逻辑,用于绑定数据,即通过使用NeedDataSource事件。

长话短说,当两者结合在一起时,它们会相互干扰,一个会覆盖另一个的行为。

  1. 动态修改网格的结构

建议使用不同的事件来更改Grid的结构,这些事件是Init和Load。

取决于使用哪个事件,需要遵循不同的方法。

请参阅Creating a RadGrid Programmatically,以找到有关如何以编程方式创建RadGrid或更改其结构的说明,而Telerik RadGrid lifecycle文章将帮助您理解原因。

有时,如果您觉得编写的代码与预期不符,则有可能为此目的使用了错误的事件序列。以下是有关此内容的更多说明的文章:RadGrid - Event sequence

以下是我想展示的几个例子:

使用Init事件时,每次页面加载时都必须创建控件及其设置

protected void Page_Init(object sender, System.EventArgs e)
{
    // create the Grid object
    RadGrid grid = new RadGrid();
    grid.ID = "RadGrid1";
    grid.DataSourceID = "SqlDataSource1";
    grid.AutoGenerateColumns = false;
    //Add Customers table  
    grid.MasterTableView.Width = Unit.Percentage(100);
    grid.MasterTableView.DataKeyNames = new string[] { "CustomerID" };

    // Attach event handlers on every postback
    RadGrid1.ItemDataBound += RadGrid1_ItemDataBound;

    // create the column object
    GridBoundColumn boundColumn = new GridBoundColumn();
    // column settings
    boundColumn.DataField = "CustomerID";
    boundColumn.HeaderText = "Customer ID";
    // add the column to the columns collection
    grid.MasterTableView.Columns.Add(boundColumn);

    // Add the grid to the placeholder  
    this.PlaceHolder1.Controls.Add(grid);
}

使用Load事件时,每次加载页面时仅需要创建Grid对象及其事件。其他所有配置(例如以编程方式添加列)都必须仅在初始加载时创建,因为ViewState会在下次在页面上显示网格时照顾它们。

protected void Page_Load(object sender, System.EventArgs e)
{
    RadGrid RadGrid1 = new RadGrid();
    RadGrid1.ID = "RadGrid1";

    // Attach event handlers on every postback
    RadGrid1.ItemDataBound += RadGrid1_ItemDataBound;

    // Add RadGrid to the Controls collection of the placeholder
    PlaceHolder1.Controls.Add(RadGrid1);

    // Configure the Grid settings, add columns, etc...
    if (!IsPostBack)
    {
        RadGrid1.DataSourceID = "SqlDataSource1";
        RadGrid1.MasterTableView.DataKeyNames = new string[] { "CustomerID" };
        RadGrid1.AllowPaging = true;
        RadGrid1.MasterTableView.AutoGenerateColumns = false;
        RadGrid1.PageSize = 15;
        GridBoundColumn boundColumn;
        boundColumn = new GridBoundColumn();
        RadGrid1.MasterTableView.Columns.Add(boundColumn);
        boundColumn.DataField = "CustomerID";
        boundColumn.HeaderText = "CustomerID";
    }
}