简体   繁体   English

单击按钮更改LinqDataSource

[英]Changing LinqDataSource with Button click

I have a GridView on my asp page. 我的ASP页面上有一个GridView。 I want to change the LinqDataSource with a button click. 我想通过单击按钮更改LinqDataSource。 it's because i have 2 database views and you have to be able to see one of these to views as you wish. 这是因为我有2个数据库视图,并且您必须能够根据需要查看其中之一。 My problems is nothing happens when I try to bind the GridView to any of my LinqDataSource'. 当我尝试将GridView绑定到任何LinqDataSource时,我的问题是什么也没有发生。

My C# code: 我的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();
    }
}

my asp code: 我的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>

it's because page_load method (event) work time page loads so it is not quite right so 这是因为page_load方法(事件)的工作时间是页面加载的,所以不太正确,所以

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

you should check page whether it has postback or not 您应该检查页面是否有回发

first of all you could try to set your datasource to null before giving it the new value and after assigning the new value you can call the refresh method of the datagrid to force it to redraw itself 首先,您可以先尝试将数据源设置为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