簡體   English   中英

單擊按鈕更改LinqDataSource

[英]Changing LinqDataSource with Button click

我的ASP頁面上有一個GridView。 我想通過單擊按鈕更改LinqDataSource。 這是因為我有2個數據庫視圖,並且您必須能夠根據需要查看其中之一。 當我嘗試將GridView綁定到任何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>

這是因為page_load方法(事件)的工作時間是頁面加載的,所以不太正確,所以

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

您應該檢查頁面是否有回發

首先,您可以先嘗試將數據源設置為null,然后再為其賦予新值,並在分配了新值之后可以調用datagrid的refresh方法來強制其重新繪制自身

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM