与Ajaxtoolkit一起使用时,ASP.Net gridview不会刷新上传控件

时间:2015-05-19 12:21:24

标签: c# asp.net ajax gridview asyncfileupload

我有一个asp.net网页,允许手动输入记录,或从excel电子表格导入以导入多个记录。

在任一进程添加记录后,它们将显示在Gridview控件中(绑定到SQLDataReader)。这允许用户在提交整个数据集进行处理之前编辑或删除记录。

我使用Ajax Toolkit AsyncFileUpload控件来处理导入。 UploadedComplete c#函数正常运行,并将记录插入SQL表中。然后代码调用我的DataBindGrid()函数来刷新网格。我可以逐步执行代码并看到每一行都在执行,但是,即使逐步完成调试,它似乎也从未真正完成。

实际上没有完成两个步骤,网格刷新和标签显示,向用户表明过程已完成。

出于测试目的,我添加了一个在单击时调用BindDataGrid()的linkBut​​ton。这可以刷新网格并显示状态标签。它不是一个永久的解决方案,让用户记住刷新风险太大,他们可能会认为他们的所有记录都已提交。

起初我认为我的问题是尝试在UploadComplete函数中做更多事情,然后只上传文件(我正在阅读上传的Excel文件),所以我打破了代码并添加了一个按钮用户单击以启动实际数据处理。这失败了,因为虽然我可以看到在UploadComplete函数期间文件名被保存为隐藏形式,但当我去读取该隐藏字段时,数据不再存在。我没有丢失任何其他隐藏字段中的值。

我已经研究了3天了,我真的卡住了。我假设我遇到了回发问题,但目前还没有任何线索。

这是我的代码:

<%@ Page Title="" Language="C#" MasterPageFile="~/WTIMS.Master" AutoEventWireup="true" CodeBehind="OptionsEntry.aspx.cs" Inherits="WTIMS_OptionsEntry.Pages.OptionsEntry" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
    <asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
        <script type="text/javascript" language=javascript>
            function uploadError(sender, args) {
                var errMsg = args.get_errorMessage();
            updateUploadStatus("error", errMsg);    
        }

        function updateUploadStatus(status, message) {
            var uploadStatLabel = document.getElementById('ContentPlaceHolder1_lblError');
            uploadStatLabel.innerText = message;
            if (status == "error") {
                uploadStatLabel.className = "LabelErrorMessage";
            }
            else {
                uploadStatLabel.className = "LabelScucessMessage";
            }
        }

        function startUpload(sender, args) {
            var fileName = args.get_fileName();
            var fileExt = fileName.substring(fileName.lastIndexOf(".") + 1);

            if (fileExt == "xlsx") {
                return true;
            }
            else {
                var err = new Error()
                err.name = "Upload Error";
                err.message = "Only .xlsx files can be uploaded";
                throw (err);
                return false;
            }
        }

        function uploadComplete(sender, args) {
            var rowCount = sender.rowCount;                     
        }
    </script> 
    <asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
    </asp:ToolkitScriptManager>

<table width = 100% cellpadding=1>
        <tr>
            <td colspan=2>
                <asp:Label ID="Label19" runat="server" Text="Upload batch" CssClass=LabelInfo></asp:Label>
            </td>            
        </tr>
        <tr>
            <td width=50%>
            <asp:AsyncFileUpload 
                    ID="AsyncFileUpload1"  
                    Width=400px 
                    ThrobberID=Throbber                    
                    UploaderStyle=Modern
                    CompleteBackColor = "#9BCD9B" 
                    ErrorBackColor="#D44942" 
                    OnClientUploadStarted="startUpload"
                    OnClientUploadError="uploadError"                    
                    OnClientUploadComplete="uploadComplete"
                    OnUploadedComplete=AsyncFileUpload1_UploadedComplete
                    OnUploadedFileError=AsyncFileUpload1_UploadedFileError
                    UploadingBackColor=AliceBlue
                    runat="server" />
                <asp:Label ID="Throbber" runat="server" Text="Label" Style="display:none">
                    <img src="../../images/LoadingWait.gif" alt="loading" />                    
                </asp:Label>                
            </td>                
        </tr>
        <tr>
            <td>
                <asp:LinkButton ID="lkbRefresh" CssClass=linkButton 
                    Text = "Records Upload, Click to View" runat="server" 
                    onclick="lkbRefresh_Click">LinkButton</asp:LinkButton>
            </td>
        </tr>
        <tr>
            <td>
                <asp:Label ID="lblError" runat="server" Text="" CssClass="LabelErrorMessage"></asp:Label>
            </td>
        </tr>
        <tr>
            <td>
                <asp:Label ID="lblStatus" runat="server" Text="" CssClass=LabelFormLabel></asp:Label>
            </td>
        </tr>
        </table>

网格的asp.net代码:

<table>
    <tr>
        <td>
            <asp:Label ID="Label18" runat="server" Text="Pending Options" CssClass=LabelInfo></asp:Label>
        </td>
    </tr>
    <tr>
        <td>
            <asp:Button ID="btnSubmit" runat="server" Text="Submit Pending Options" 
                CssClass=button onclick="btnSubmit_Click" />
        </td>
    </tr>
    <tr>
        <td>
            <asp:GridView ID="grdOptions"  
            runat="server" 
            AutoGenerateColumns="False" 
            DataKeyNames="OptionRecordID" 
            EmptyDataText="You Have no pending Options" 

            onrowdatabound="grdOptions_RowDataBound">
            <FooterStyle CssClass="FooterStyle" />
            <HeaderStyle CssClass="HeaderStyle" />
            <RowStyle CssClass="RowStyle" />
            <AlternatingRowStyle CssClass="AlternatingRowStyle" />
            <PagerStyle CssClass="PagerStyle" />                    
                <Columns>
                    <asp:TemplateField>
                     <EditItemTemplate>
                        <asp:LinkButton ID="lkbSave" runat="server" Text= "Save" CssClass=linkButton onclick="lkbSave_Click"></asp:LinkButton> &nbsp;&nbsp;
                        <asp:LinkButton ID="lkbCancek" runat="server" Text="Cancel" CssClass=linkButton onclick="lkbCancel_Click"></asp:LinkButton>
                    </EditItemTemplate> 
                    <ItemTemplate>
                        <asp:LinkButton ID="lkbEdit" runat="server" Text= "Edit" CssClass=linkButton onclick="lkbEdit_Click"></asp:LinkButton>
                    </ItemTemplate>           
                 </asp:TemplateField>
                    <asp:TemplateField HeaderText="OptionRecordID" InsertVisible="False" 
                        SortExpression="OptionRecordID" Visible="False">
                        <EditItemTemplate>
                            <asp:Label ID="lblOptionIDEdit" runat="server" Text='<%# Eval("OptionRecordID") %>'></asp:Label>
                        </EditItemTemplate>
                        <ItemTemplate>
                            <asp:Label ID="lblOptionID" runat="server" Text='<%# Bind("OptionRecordID") %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="SecurityID" SortExpression="SecurityID">
                        <ItemTemplate>
                            <asp:Label ID="Label2" runat="server" Text='<%# Bind("SecurityID") %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="Symbol" SortExpression="Symbol">
                        <EditItemTemplate>
                            <asp:TextBox ID="txtSymbolEdit" Width=75px runat="server" Text='<%# Bind("Symbol") %>'></asp:TextBox>
                        </EditItemTemplate>
                        <ItemTemplate>
                            <asp:Label ID="Label3" runat="server" Text='<%# Bind("Symbol") %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="Call/Put" SortExpression="CallPut">
                        <EditItemTemplate>
                            <asp:DropDownList ID="ddlPutCallEdit" runat="server" CssClass=dropdownList SelectedValue='<%# Bind("CallPut") %>'>
                                <asp:ListItem Text="Select" Value="Select"></asp:ListItem>
                                <asp:ListItem Text ="Put" Value = "Put"></asp:ListItem>
                                <asp:ListItem Text ="Call" Value = "Call"></asp:ListItem>
                            </asp:DropDownList>
                        </EditItemTemplate>
                        <ItemTemplate>
                            <asp:Label ID="Label4" runat="server" Text='<%# Bind("CallPut") %>'></asp:Label>                               
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="Buy Write" SortExpression="BuyWrite">
                        <EditItemTemplate>
                             <asp:DropDownList ID="ddlWtriteBuyEdit" runat="server" CssClass=dropdownList SelectedValue='<%# Bind("BuyWrite") %>'>
                                <asp:ListItem Text="Select" Value="Select"></asp:ListItem>
                                <asp:ListItem Text ="Buy" Value = "Buy"></asp:ListItem>
                                <asp:ListItem Text ="Write" Value = "Write"></asp:ListItem>
                            </asp:DropDownList>
                        </EditItemTemplate>
                        <ItemTemplate>
                            <asp:Label ID="Label8" runat="server" Text='<%# Bind("BuyWrite") %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="Price" SortExpression="Price">
                        <EditItemTemplate>
                            <asp:TextBox ID="txtPriceEdit" Width=75px runat="server" Text='<%# Bind("Price") %>'></asp:TextBox>
                        </EditItemTemplate>
                        <ItemTemplate>
                            <asp:Label ID="Label5" runat="server" Text='<%# Bind("Price") %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="Expiration Date" SortExpression="ExpirationDate">
                        <EditItemTemplate>
                            <asp:TextBox ID="txtExpirationDateEdit" Width=100px runat="server" Text='<%# Convert.ToDateTime(Eval("ExpirationDate")).ToString("d")  %>'></asp:TextBox>
                        </EditItemTemplate>
                        <ItemTemplate>
                            <asp:Label ID="Label6" runat="server" Text='<%# Convert.ToDateTime(Eval("ExpirationDate")).ToString("d") %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:TemplateField HeaderText="Description" SortExpression="Description">
                        <EditItemTemplate>
                            <asp:TextBox ID="txtDescriptionEdit" runat="server" Text='<%# Bind("Description") %>'></asp:TextBox>
                        </EditItemTemplate>
                        <ItemTemplate>
                            <asp:Label ID="Label7" runat="server" Text='<%# Bind("Description") %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>                        

                    <asp:TemplateField HeaderText="UploadStatus" SortExpression="UploadStatus">
                        <ItemTemplate>
                            <asp:Label ID="lblStatus" runat="server" Text='<%# Bind("UploadStatus") %>'></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>

                    <asp:TemplateField>
                        <ItemTemplate>
                            <asp:LinkButton ID="lkbDelete" runat="server" CssClass=linkButton Text="Delete" onclick="lkbDelete_Click"></asp:LinkButton>
                        </ItemTemplate>
                    </asp:TemplateField>
                </Columns>
            </asp:GridView>

        </td>
    </tr>
</table>

C#代码:

    protected void AsyncFileUpload1_UploadedComplete(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
                {
                strFileName = Server.MapPath("~/Files/" + this.hdnSessionID.Value + "_uploaded.xlsx");
                string strUploadFileName = AsyncFileUpload1.FileName.ToString();
                InsertData.InsertLogMessage("File to upload: " + strFileName, "OptionsEntry", this.hdnUserID.Value);
                this.hdnUploadFileName.Value = strFileName;
                AsyncFileUpload1.SaveAs(strFileName);
                InsertData.InsertLogMessage("File saved: " + strFileName, "OptionsEntry", this.hdnUserID.Value);
                UploadData(strFileName);
                DataBindGrid();
                }

protected void UploadData(string strUploadFileName)
                {     //process the file that was uploaded
                try
                    {
                    InsertData.InsertLogMessage("Starting Upload", "OptionsEntry", this.hdnUserID.Value);
                    int i = 0;
                    // string strFileName = this.hdnUploadFileName.Value;

                    FileStream myStream = File.Open(strUploadFileName, FileMode.Open, FileAccess.Read);
                    IExcelDataReader myReader = ExcelReaderFactory.CreateOpenXmlReader(myStream);
                    myReader.IsFirstRowAsColumnNames = true;
                    DataSet result = myReader.AsDataSet();

                    foreach (DataTable dt in result.Tables)
                        {

                        foreach (DataRow dr in dt.Rows)
                            {
                            Boolean blnIsValid = true;
                            //code here to loop through file and insert records
                            InsertData.InsertOptionEntryFormData(strSymbol, strCallPut, strUnformattedPrice, dtmExpirationDate, strDescription, strBuyWrite, this.hdnUserID.Value, strTicker, strStatus);

                            i = i + 1;
                            }
                        }
                    this.lblStatus.Text = i + " records have been imported to the pending table.  Please review and correct any errors before submitting.";
                    InsertData.InsertLogMessage( i + " records have been imported", "OptionsEntry", this.hdnUserID.Value);
                    DataBindGrid();
                    }
                catch (Exception ex)
                    {
                    InsertData.InsertLogMessage("An error occured: " + ex.Message, "OptionsEntry", this.hdnUserID.Value);
                    this.lblStatus.Text = "There was a problem importing the data, please check the file and try again.";
                    }    
                }

            protected void DataBindGrid()
                {
                    this.grdOptions.DataSource = GetData.GetOptionEntryFormData(this.hdnUserID.Value);
                    this.grdOptions.DataBind();                
                }

任何建议都将不胜感激!

编辑 - grdOptions的代码

protected void grdOptions_RowDataBound(object sender, GridViewRowEventArgs e)
            {
            if (e.Row.RowType == DataControlRowType.DataRow)
                {
                Label lblStatus = (Label)e.Row.Cells[9].Controls[1];
                if (lblStatus.Text == "Invalid")
                    {
                    e.Row.CssClass = "RowError";
                    }
                else
                    {
                    if (e.Row.RowState == DataControlRowState.Alternate)
                        {
                        e.Row.CssClass = "AlternatingRowStyle";
                        }
                    else
                        {
                        e.Row.CssClass = "RowStyle";
                        }

                    }

                }

            }

#region Grid Link Actions
        protected void lkbSave_Click(object sender, EventArgs e)
            {
            this.lblErrorMessage.Visible = false;
            ClearFormColor();
            Boolean blnIsValid = true;  //start off assuming everthing is valid
            //get the row that we are sitting on
            WebControl wc = (WebControl)sender;
            GridViewRow row = (GridViewRow)wc.NamingContainer;


            //get the data we need
            Label lblOptionIDEdit = (Label)row.FindControl("lblOptionIDEdit");
            int intOptionIDEdit = int.Parse(lblOptionIDEdit.Text);

            TextBox txtSymbolEdit = (TextBox)row.FindControl("txtSymbolEdit");
            strSymbol = txtSymbolEdit.Text;
            if(!ValidateSymbol())
                {
                    ToggleTextBoxColor(false,txtSymbolEdit);
                    blnIsValid = false;
                }

            DropDownList ddlPutCallEdit = (DropDownList)row.FindControl("ddlPutCallEdit");
            strCallPut = ddlPutCallEdit.SelectedValue;
            if(!ValidateCallPut())
                {
                    ToggleDropDownColor(false,ddlPutCallEdit);
                    blnIsValid = false;
                }

            DropDownList ddlWtriteBuyEdit = (DropDownList)row.FindControl("ddlWtriteBuyEdit");
            strBuyWrite = ddlWtriteBuyEdit.SelectedValue;
            if(!ValidateBuyWrite())
                {
                    ToggleDropDownColor(false,ddlWtriteBuyEdit);
                    blnIsValid= false;
                }

            TextBox txtPriceEdit = (TextBox)row.FindControl("txtPriceEdit");
            strPrice = txtPriceEdit.Text;
            if(!ValidateStrikePrice())
                {
                    ToggleTextBoxColor(false,txtPriceEdit);
                    blnIsValid= false;
                }


            TextBox txtExpirationDateEdit = (TextBox)row.FindControl("txtExpirationDateEdit");
            strExpirationDate = txtExpirationDateEdit.Text;
            if(!ValidateExpirationDate())
                {
                    ToggleTextBoxColor(false,txtExpirationDateEdit);
                    blnIsValid = false;
                }

            TextBox txtDescriptionEdit = (TextBox)row.FindControl("txtDescriptionEdit");
            strDescription = txtDescriptionEdit.Text;

            if(!blnIsValid)
                {
                    this.lblErrorMessage.Text = "Please corrext the data highlighted in yellow";
                    this.lblErrorMessage.Visible= true;
                return;
                }

            FormatTicker();
            //update the data
            UpdateData.UpdateOptionEntryFormData(intOptionIDEdit, strSymbol, strCallPut, strUnformattedPrice, dtmExpirationDate, strDescription, strBuyWrite, strTicker, "Manual");

            //refresh the grid
            this.grdOptions.EditIndex = -1;
            DataBindGrid();

            }

        protected void lkbEdit_Click(object sender, EventArgs e)
            {
            WebControl wc = (WebControl)sender;
            GridViewRow row = (GridViewRow)wc.NamingContainer;
            int intIndex = row.RowIndex;

            this.grdOptions.EditIndex = intIndex;
            DataBindGrid();
            }           

        protected void lkbDelete_Click(object sender, EventArgs e)
            {
            //get the row that we are sitting on
            WebControl wc = (WebControl)sender;
            GridViewRow row = (GridViewRow)wc.NamingContainer;

            //get the data we need
            Label lblRecordID = (Label)row.FindControl("lblOptionID");
            int intRecordID = int.Parse(lblRecordID.Text);

            //delete the record
            DeleteData.DeleteOption(intRecordID);

            //refresh the grid
            DataBindGrid();
            }

        protected void lkbCancel_Click(object sender, EventArgs e)
    {
        this.grdOptions.EditIndex = -1;
    }


        #endregion

0 个答案:

没有答案