2009-12-24 2 views
0

계절에 맞춰 인사드립니다. 이것이 나를 미치게 만드는 데 도움이 필요합니다.Gridview 분류, 업데이트 및 편집

목표입니다. 나는 클라이언트가 숫자를 입력하는 텍스트 박스를 가지고 있으며, 라디오 버튼 목록을 클릭하여 머티리얼을 선택하고 버튼을 눌러 그리드 뷰를 채 웁니다.

이 프런트 엔드 코드 :

<asp:TextBox ID="tbxHowMany" runat="server" 
     style="z-index: 1; left: 300px; top: 250px; position: absolute"></asp:TextBox> 

    <asp:Button ID="btnDisplayTopReport" runat="server" 
     style="z-index: 1; left: 645px; top: 285px; position: absolute; height: 25px; width: 170px" 
     Text="Display TOP Report" onclick="btnDisplayTopReport_Click" /> 

    <asp:RadioButtonList ID="radTOP" runat="server" 
     style="z-index: 1; left: 575px; top: 180px; position: absolute; height: 177px; width: 86px"> 
     <asp:ListItem>Paper</asp:ListItem> 
     <asp:ListItem>Glass</asp:ListItem> 
     <asp:ListItem>Aluminium</asp:ListItem> 
     <asp:ListItem>Steel</asp:ListItem> 
     <asp:ListItem>Plastic</asp:ListItem> 
     <asp:ListItem>Wood</asp:ListItem> 
     <asp:ListItem>Other</asp:ListItem> 
    </asp:RadioButtonList> 

    <asp:LinqDataSource ID="LQTOPReportDS" runat="server" 
     ContextTypeName="CompleteWeightsDataContext" 
     EnableUpdate="True" TableName="tblOnlineReportingCOMPLETEWeights" 
     Where="IDDesc == @IDDesc && UnitUserfield1 == @UnitUserfield1 && UnitUserfield2 == @UnitUserfield2 && MaterialLevel == @MaterialLevel" 
     OrderBy="UnitId, MaterialLevel, MaterialText, UnitWeight" 
     StoreOriginalValuesInViewState="True"> 
    </asp:LinqDataSource> 

    <asp:GridView ID="GridView1" runat="server" AllowPaging="True" 
     AllowSorting="True" AutoGenerateColumns="False" CellPadding="4" 
     DataKeyNames="PriKey" DataSourceID="LQTOPReportDS" ForeColor="#333333" 
     GridLines="None" Font-Size="X-Small" 
     style="z-index: 1; left: 5px; top: 375px; position: absolute; height: 133px; width: 187px" 
     onpageindexchanging="GridView1_PageIndexChanging" 
      onrowediting="GridView1_RowEditing" onrowupdating="GridView1_RowUpdating" 
      onsorting="GridView1_Sorting"> 
     <RowStyle BackColor="#F7F6F3" ForeColor="#333333" /> 
     <Columns> 
      <asp:CommandField ShowEditButton="True" /> 
      <asp:BoundField DataField="UnitId" HeaderText="UnitId" 
       SortExpression="UnitId" /> 
      <asp:BoundField DataField="UnitDescription" HeaderText="UnitDescription" 
       SortExpression="UnitDescription" /> 
      <asp:BoundField DataField="PackagingGroupId" HeaderText="PackagingGroupId" 
       SortExpression="PackagingGroupId" /> 
      <asp:CheckBoxField DataField="IsPackagingGroup" HeaderText="IsPackagingGroup" 
       SortExpression="IsPackagingGroup" /> 
      <asp:BoundField DataField="PackagingTypeCode" HeaderText="PackagingTypeCode" 
       SortExpression="PackagingTypeCode" /> 
      <asp:BoundField DataField="UnitWeight" HeaderText="UnitWeight" 
       SortExpression="UnitWeight" /> 
      <asp:BoundField DataField="WeightUnitCode" HeaderText="WeightUnitCode" 
       SortExpression="WeightUnitCode" /> 
      <asp:BoundField DataField="MaterialLevel" HeaderText="MaterialLevel" 
       SortExpression="MaterialLevel" /> 
      <asp:BoundField DataField="MaterialText" HeaderText="MaterialText" 
       SortExpression="MaterialText" /> 
      <asp:BoundField DataField="ProductPercentage" HeaderText="ProductPercentage" 
       SortExpression="ProductPercentage" /> 
      <asp:BoundField DataField="UnitUserfield2" HeaderText="UnitUserfield2" 
       SortExpression="UnitUserfield2" /> 
      <asp:BoundField DataField="Comment" HeaderText="Comment" 
       SortExpression="Comment" /> 

     </Columns> 
     <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" /> 
     <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" /> 
     <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" /> 
     <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" /> 
     <EditRowStyle BackColor="#999999" /> 
     <AlternatingRowStyle BackColor="White" ForeColor="#284775" /> 
    </asp:GridView> 

그리고 이것은 뒤에 코드 :

public partial class TOP : System.Web.UI.Page 
{ 
    protected void Page_Load(object sender, EventArgs e) 
    { 
     if (!IsPostBack) 
     { 
      Session["MemberKey"] = "FM00012"; 

      GridView1.DataSourceID = null; 
      GridView1.DataBind(); 
     } 
    } 

    private object GetMaterialData(string MemberKey, string MaterialType, string MaterialLevel, int Count) 
    { 
     CompleteWeightsDataContext db = new CompleteWeightsDataContext(); 
     var query = db.tblOnlineReportingCOMPLETEWeights 
        .Where(x => x.MemberId == MemberKey && x.MaterialText == MaterialType && x.MaterialLevel == MaterialLevel) 
        .OrderByDescending(x => x.ProductPercentage) 
        .Take(Count); 
     return query; 
     } 

     protected void btnDisplayTopReport_Click(object sender, EventArgs e) 
    { 
     GridView1.DataSourceID = null; 
     GridView1.DataBind(); 

     if (radTOP.SelectedValue == "" || tbxHowMany.Text == "") 
     { 
      MessageBox.Show("Please Ensure that BOTH 'The Number of Products' and Appropriate material Is selected Before You Attempt To Run a TOP X Report", "Top X Error!!!", 
       MessageBoxButtons.OK, MessageBoxIcon.Exclamation); 
      GridView1.DataSourceID = null; 
      GridView1.DataBind(); 
     } 
     else 
     { 
      int max = 0; 
      if (int.TryParse(tbxHowMany.Text, out max)) 
      { 
       GridView1.DataSource = GetMaterialData(Session["MemberKey"].ToString(), radTOP.SelectedItem.Value, "Primary", max); 
       GridView1.DataBind(); 
      } 
     } 
    } 


    protected void GridView1_Sorting(object sender, GridViewSortEventArgs e) 
    { 

    } 

} 

지금 내가 정렬 이벤트를 채울 알고하지만 난 sooo를 다양한 조합을 시도했다, 나는 올바른 픽크레 (그러므로 null!)에 자신을 가지고있다.

나는 gridview를 채우기 위해 사용하는 linq가 테이크를 사용하므로, 정렬이 실행될 때 데이터가 손실 될 수 있다고 생각합니다.

누군가 올바른 방향으로 나를 가리켜 주시겠습니까? 마찬가지로, 내가 행운을 빕니다 및 rowediting와 비슷한 문제가 발생할 것입니다 그래서 만약 내가 원하는 결과를 달성하기위한 제안을 할 수 있다면, 나는 가장 감사하게 될 것입니다 ... 사실, 당신은 내 지역에서 축제 음료에 가입 할 환영합니다. !

답변

0

당신이 무엇을 하려는지 완전히 모르겠지만 일반적으로 정렬 처리기는 gridview에서 열을 정렬하는 데 사용됩니다. 아래 샘플 코드에서는 오름차순 또는 내림차순으로 정렬을 처리하고 캐싱을 사용하므로 열을 기준으로 데이터베이스를 다시 정렬 할 필요가 없습니다.

일반적으로 눈금보기의 데이터 소스를 업데이트하고 정렬 된 결과로 다시 바인딩하려고합니다.

/// <summary> 
/// <para>Event handler for sorting items in the grid. It allows the user to sort by any column in the grid. 
/// The method makes use of caching to reduce access to the persistence layer.</para> 
/// </summary> 
/// <param name="sender">The sender which triggered the event.</param> 
/// <param name="e">The event arguments.</param> 
protected void gvFileList_Sorting(object sender, GridViewSortEventArgs e) 
{ 
    string sortExpression; 

    DataSet ds = (DataSet)HttpRuntime.Cache[Session.SessionID + "dsFileList"]; 
    if (ds == null) 
    { 
     LoadGridData(); 
     ds = (DataSet)HttpRuntime.Cache[Session.SessionID + "dsFileList"]; 
    } 
    ds.Tables[0].DefaultView.Sort = e.SortExpression; 

    // check the cache to see if user has sorted by this column (i.e. this SortExpression) 
    // previously, and if they have, reverse the sort direction 
    if (HttpRuntime.Cache[Session.SessionID + "dsFileList" + e.SortExpression] != null) 
    { 
     // get the previous sort direction from the cache 
     string dir = (string)HttpRuntime.Cache[Session.SessionID + "dsFileList" + e.SortExpression]; 

     // reverse the sort direction and update the cache 
     if (dir == "ASC") 
     { 
      Helper.AddToCache(Session.SessionID + "dsFileList" + e.SortExpression, "DESC", 120); 
      ds.Tables[0].DefaultView.Sort += " DESC"; 
      sortExpression = e.SortExpression + " DESC"; 
     } 
     else 
     { 
      Helper.AddToCache(Session.SessionID + "dsFileList" + e.SortExpression, "ASC", 120); 
      ds.Tables[0].DefaultView.Sort += " ASC"; 
      sortExpression = e.SortExpression + " ASC"; 
     } 
    } 
    else 
    { 
     // this column has not been sorted on previously, so update the cache with 
     // sort direction = ASC for this column since ascending is the initial 
     // sort direction 
     Helper.AddToCache(Session.SessionID + "dsFileList" + e.SortExpression, "ASC", 120); 
     sortExpression = e.SortExpression + " ASC"; 
    } 

    gvFileList.DataSource = ds.Tables[0].DefaultView; 
    gvFileList.DataBind(); 

    // store the sort expression in cache so that when the grid is refreshed by the tmTFFileList_Tick 
    // method, we can get the sort expression to use 
    Helper.AddToCache(Session.SessionID + "dsFileList.SortExpression", sortExpression, 120); 
}