После применения фильтра к linqdatasource, подключенному к GridView, нажатие кнопки «Изменить» возвращает меня к старым данным. - PullRequest
0 голосов
/ 19 июля 2011

Как однажды сказал картинка стоимостью в тысячу слов The original data before applying the filter

After applying the filter , Now I'm going to press edit button

, когда я нажимаю кнопку редактирования, я возвращаюсь к старым данным, с первой строкой в ​​редактировании.режим, подобный следующему The Problem

это код, который я использую при поиске по имени студента или дате ....

LinqDataSource1.Where = "pay_date.Contains(" + 

(Convert.ToString(Convert.ToDateTime(TextBox1.Text))) + ")";

Я пытался использовать AJAX, не сработалоЯ нашел в linqdatasource свойство linqdatasource storeoriginalvaluesinviewstate
Я сделал это ложным, но все та же проблема,

.ascx

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="EDPayment.ascx.cs" Inherits="Admin_ED_EDPayment" %>

    <asp:ScriptManagerProxy ID="ScriptManagerProxy1" runat="server">
        <Services>
        <asp:ServiceReference Path="~/Admin/ED/Student_AutoComplete.asmx" />            
        </Services>        
    </asp:ScriptManagerProxy>
        <br />

<asp:UpdatePanel ID="UpdatePanel1" runat="server">
    <ContentTemplate>
            <div>
            <asp:Label ID="Label3" runat="server" 
    Text="Search By Student Name:"></asp:Label>
            <asp:TextBox runat="server" ID="myTextBox" Width="300" ontextchanged="myTextBox_TextChanged" />
            <asp:autocompleteextender
                runat="server" 
                ID="autoComplete1" 
                TargetControlID="myTextBox"
                ServicePath="~/Admin/ED/Student_AutoComplete.asmx"
                ServiceMethod="GetCompletionList"
                MinimumPrefixLength="1" 
                CompletionInterval="1000"
                EnableCaching="true"
                CompletionSetCount="12" />
                &nbsp;<asp:Button ID="Button1" runat="server" onclick="Button1_Click" 
                    Text="Search" />
                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        <br />
<br />
<asp:Label ID="Label4" runat="server" Text="Search By Date:"></asp:Label>
<asp:TextBox ID="TextBox1" runat="server" ontextchanged="TextBox1_TextChanged"></asp:TextBox>
<asp:CalendarExtender ID="TextBox1_CalendarExtender" runat="server" 
    BehaviorID="TextBox1_CalendarExtender" Enabled="True" 
    TargetControlID="TextBox1">
</asp:CalendarExtender>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<asp:Button ID="Button2" runat="server" onclick="Button2_Click" Text="Search" />
    <br />
<br />
<asp:Button ID="Button3" runat="server" onclick="Button3_Click" 
    Text="Search By Date &amp; Name" />
    <br />
<asp:Label ID="Label5" runat="server"></asp:Label>
    <br />
<asp:Button ID="Button4" runat="server" onclick="Button4_Click" 
    Text="Show All Payments" /></div>

        <asp:GridView ID="GridView1" runat="server" AllowPaging="True" 
    AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="pay_id" 
    DataSourceID="LinqDataSource1" onrowediting="GridView1_RowEditing">
            <Columns>
                <asp:CommandField ShowDeleteButton="True" ShowEditButton="True" />
                <asp:BoundField DataField="pay_id" HeaderText="pay_id" InsertVisible="False" 
            ReadOnly="True" SortExpression="pay_id" />
                <asp:BoundField DataField="pay_amount" HeaderText="pay_amount" 
            SortExpression="pay_amount" />
                <asp:BoundField DataField="pay_date" HeaderText="pay_date" 
            SortExpression="pay_date" />
                <asp:TemplateField HeaderText="pay_st_id" SortExpression="pay_st_id">
                    <EditItemTemplate>
                        <asp:DropDownList ID="DropDownList1" runat="server" 
                    DataSourceID="LinqDataSource2" DataTextField="st_fullname" 
                    DataValueField="st_id" SelectedValue='<%# Bind("pay_st_id") %>'>
                        </asp:DropDownList>
                        <asp:LinqDataSource ID="LinqDataSource2" runat="server" 
                    ContextTypeName="TeacherAssistantDataContext" 
                    OrderBy="st_fname, st_mname, st_lname" Select="new (st_fullname, st_id)" 
                    TableName="students">
                        </asp:LinqDataSource>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="Label1" runat="server" Text='<%# Bind("pay_st_id") %>' 
                    Visible="False"></asp:Label>
                        <asp:DropDownList ID="DropDownList2" runat="server" 
                    DataSourceID="LinqDataSource3" DataTextField="st_fullname" 
                    DataValueField="st_id" Enabled="False">
                        </asp:DropDownList>
                        <asp:LinqDataSource ID="LinqDataSource3" runat="server" 
                    ContextTypeName="TeacherAssistantDataContext" 
                    OrderBy="st_fname, st_mname, st_lname" Select="new (st_id, st_fullname)" 
                    TableName="students" Where="st_id == @st_id">
                            <WhereParameters>
                                <asp:ControlParameter ControlID="Label1" Name="st_id" PropertyName="Text" 
                            Type="Int32" />
                            </WhereParameters>
                        </asp:LinqDataSource>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
            <asp:LinqDataSource ID="LinqDataSource1" runat="server" 
                ContextTypeName="TeacherAssistantDataContext" EnableDelete="True" 
                EnableUpdate="True" OrderBy="pay_date, pay_amount, pay_st_id" 
                TableName="payments">
            </asp:LinqDataSource>
    </ContentTemplate>
</asp:UpdatePanel>

.ascx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Admin_ED_EDPayment : System.Web.UI.UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        go1();
    }
    protected void go1()
    {       
        int[] id = Searcher._Student.searchByst_fullName2(myTextBox.Text);
        LinqDataSource1.Where = "pay_st_id == " + id[0].ToString();
       // Parameter p = new Parameter("", System.Data.DbType.Int32, id[0].ToString());
        //LinqDataSource1.WhereParameters.Add(p);
       // LinqDataSource1.DataBind();
        //fix();

    }
    protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
    {

    }
    protected void Button2_Click(object sender, EventArgs e)
    {
        go2();
    }
    protected void go2()
    {
        LinqDataSource1.Where = "pay_date == DateTime.Parse(\"" + TextBox1.Text + "\")";

        fix();
    }
    void fix()
    {
    //    LinqDataSource1.
    }
    protected void Button3_Click(object sender, EventArgs e)
    {
        int[] id = Searcher._Student.searchByst_fullName2(myTextBox.Text);
        LinqDataSource1.Where = "pay_st_id == " + id[0].ToString() + " AND " + "pay_date == DateTime.Parse(\"" + TextBox1.Text + "\")";
    }
    protected void myTextBox_TextChanged(object sender, EventArgs e)
    {
        go1();
    }
    protected void TextBox1_TextChanged(object sender, EventArgs e)
    {
        go2();
    }

    protected void Button4_Click(object sender, EventArgs e)
    {
        LinqDataSource1.TableName = "payments";
        LinqDataSource1.DataBind();        
    }
    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {

    }
* *} тысяча двадцать-один

Ответы [ 2 ]

1 голос
/ 19 июля 2011

Я думаю, что вы должны поместить свой код в загрузку страницы, а не в нажатие кнопки, а затем сначала проверить, содержит ли текстовое поле данные, и содержит ли оно данные, примените свой фильтр.

Думаю, ваша проблема в том, что когда страница загружается во второй раз, вызывается функция привязки данных, которая снова получает все данные.

попробуйте это обновление

<asp:LinqDataSource ID="LinqDataSource3" runat="server" 
                    ContextTypeName="TeacherAssistantDataContext"   OnSelected="LinqDataSource1_Selected"
                    OrderBy="st_fname, st_mname, st_lname" Select="new (st_id, st_fullname)" 
                    TableName="students" Where="st_id == @st_id">
                            <WhereParameters>
                                <asp:ControlParameter ControlID="Label1" Name="st_id" PropertyName="Text" 
                            Type="Int32" />
                            </WhereParameters>
                        </asp:LinqDataSource>

Код позади:

protected void LinqDataSource1_Selected(object sender, LinqDataSourceStatusEventArgs e)
    {
        if(!string.IsNullOrEmpty( myTextBox.Text))
        {
            go1();
        }
        if(!string.IsNullOrEmpty( TextBox1.Text))
        {
            go2();
        }
    }
0 голосов
/ 21 июля 2011

Я нашел решение, основанное на этой теме: Как я могу предотвратить сброс условия LinqDataSource Where при обратной передаче? : Источник Все, что мне нужно, это сохранить предложение where в linqdatasource и перезагрузить его снова в событии page_load, чтобы окончательный код стал

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Admin_ED_EDPayment : System.Web.UI.UserControl
{
    //private Boolean b1 = false, b2 = false, b3 = false;
    public string MyLinqSourceWhere
    {
        get { return (string)this.ViewState["MyLinqSourceWhere"]; }
        set { this.ViewState["MyLinqSourceWhere"] = value; }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        this.LinqDataSource1.Where = this.MyLinqSourceWhere;
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        go1();
    }
    protected void go1()
    {       
        int[] id = Searcher._Student.searchByst_fullName2(myTextBox.Text);
        this.MyLinqSourceWhere = "pay_st_id == " + id[0].ToString();
        this.LinqDataSource1.Where = this.MyLinqSourceWhere;
    }
    protected void go3()
    {
        int[] id = Searcher._Student.searchByst_fullName2(myTextBox.Text);
        this.MyLinqSourceWhere = "pay_st_id == " + id[0].ToString() + " AND " + "pay_date == DateTime.Parse(\"" + TextBox1.Text + "\")";
        this.LinqDataSource1.Where = this.MyLinqSourceWhere;
    }
    protected void Button2_Click(object sender, EventArgs e)
    {
        go2();        
    }
    protected void go2()
    {
        this.MyLinqSourceWhere = "pay_date == DateTime.Parse(\"" + TextBox1.Text + "\")";
        this.LinqDataSource1.Where = this.MyLinqSourceWhere;
    }
    protected void Button3_Click(object sender, EventArgs e)
    {
        go3();
    }
    protected void myTextBox_TextChanged(object sender, EventArgs e)
    {
        go1();
    }
    protected void TextBox1_TextChanged(object sender, EventArgs e)
    {
        go2();
    }

    protected void Button4_Click(object sender, EventArgs e)
    {
        LinqDataSource1.TableName = "payments";
        LinqDataSource1.DataBind();        
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...