2012-10-31 59 views
0

我的asp頁面上有一個GridView。我想用按鈕單擊來更改LinqDataSource。這是因爲我有2個數據庫視圖,您必須能夠根據需要查看其中的一個視圖。當我嘗試將GridView綁定到我的任何LinqDataSource時,我的問題不會發生。用按鈕改變LinqDataSource點擊

我的C#代碼:

protected void Page_Load(object sender, EventArgs e) 
{ 
    this.Grid.DataSource = lqds_Grid1; 
    this.Grid.DataBind(); 
} 

protected void Button1_Click(object sender, EventArgs e) 
{ 
    if (this.Grid.DataSource == lqds_Grid1) 
    { 
     this.Grid.DataSource = lqds_Grid2; 
     this.Grid.DataBind(); 
    } 
    else 
    { 
     this.Grid.DataSource = lqds_Grid1; 
     this.Grid.DataBind(); 
    } 
} 

我的ASP代碼:

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" 
    CodeBehind="Default.aspx.cs" Inherits="AddressReporting._Default" %> 

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent"> 
</asp:Content> 
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent"> 
    <asp:LinqDataSource ID="lqds_Grid1" runat="server" 
     ContextTypeName="AddressReporting.MobileGateway" EntityTypeName="" 
     OrderBy="AdrID, Country" TableName="BarcodeWithLocation"> 
    </asp:LinqDataSource> 
    <asp:LinqDataSource ID="lqds_Grid2" runat="server" 
     ContextTypeName="AddressReporting.MobileGateway" EntityTypeName="" 
     OrderBy="AdrID, Country" TableName="BarcodeWithLocationSorted"> 
    </asp:LinqDataSource> 
    <asp:GridView ID="Grid" runat="server" AllowPaging="True" 
     AutoGenerateColumns="False" Height="217px" Width="268px"> 
</asp:GridView> 
    <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" /> 
</asp:Content> 
+0

哪裏是格列? –

+0

它們從數據庫中檢索 – Lahib

+1

它們不像您設置的那樣'AutoGenerateColumns =「False」' –

回答

1

它是因爲page_load方法(事件)的工作時間頁面加載所以它是不完全正確所以

protected void Page_Load(object sender, EventArgs e) 
{ 
    if(!isPostBack) { 
     this.Grid.DataSource = lqds_Grid1; 
     this.Grid.DataBind(); 
    } 
} 

你應該檢查網頁是否有回發或不

+0

這意味着如果頁面首次加載,那麼數據源是'lqds_Grid1',否則如果有回發比Page_load沒有改變任何東西,所以'lqds_Grid2'必須工作 – RustamIS

+0

即時通訊新的在asp,所以我在哪裏設置此回發屬性? – Lahib

+0

找到了!謝謝! – Lahib

0

首先,你可以嘗試給它新的價值之前,設置你的數據源,以零和分配新值後的你可以調用數據網格的刷新方法來強制它重繪自己

this.Grid.DataSource = null; 
this.Grid.DataSource = lqds_Grid1; 
this.Grid.DataBind(); 
this.Grid.DataSource.Refresh();