2

I have an asp.net gridview and the data in the gridview is populated from an excel file and I seek to edit the file using the gridview and save the edits, however when a row is selected for editing the values for that selected row are not可见的。如果我将数据重新绑定到网格视图,它就会消失。如何在编辑时保持所选行上值的可见性?

    <form id="form1" runat="server">
<div>
          <asp:ScriptManager runat="server" />
           <asp:UpdatePanel ID="grdUpdatePanel" runat="server" UpdateMode="Conditional">
               <ContentTemplate>
                    <asp:GridView ID="gridViewTest" runat="server" OnRowDataBound="gv_RowDataBound" OnRowEditing="gv_RowEditing">
                    </asp:GridView>
               </ContentTemplate>
           </asp:UpdatePanel>
</div>
<br/>
<div>
    <asp:Button ID="btnExport" runat="server" Text="Export" 
        onclick="btnExport_Click" />&nbsp;&nbsp;
    <asp:FileUpload ID="UploadField"
        runat="server" />&nbsp;<asp:Button ID="btnImport" runat="server" Text="Import" 
        onclick="btnImport_Click" />
    </div>
</form>

public partial class ExportAndImportExcel : System.Web.UI.Page
{

    internal DataTable dt = new DataTable();


    protected void Page_Load(object sender, EventArgs e)
    {
        // Disable Export button
        this.btnExport.Enabled = false;

    }

     #region Import operation

    /// <summary>
    ///  Import Excel Data into GridView Control 
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    /// 


    protected void btnImport_Click(object sender, EventArgs e)
    {


        // The condition that FileUpload control contains a file 
        if (UploadField.HasFile)
        {
            // Get selected file name
            string filename = Server.MapPath(UploadField.FileName);

            // Get the extension of the selected file
            string fileExten = Path.GetExtension(filename);


            // The condition that the extension is not xlsx
            if (!fileExten.Equals(".xlsx", StringComparison.OrdinalIgnoreCase))
            {
                Response.Write("<script language=\"javascript\">alert('The extension of selected file is incorrect ,please select again');</script>");
                return;
            }

            // Read Data in excel file
            try
            {

               dt = ReadExcelFile(filename);

                if (dt.Rows.Count == 0)
                {
                    Response.Write("<script language=\"javascript\">alert('The first sheet is empty.');</script>");
                    return;
                }

                // Bind Datasource
                this.gridViewTest.DataSource = dt;
                this.gridViewTest.DataBind();

                // Enable Export button
                this.btnExport.Enabled = true;
            }
            catch (IOException ex)
            {
                string exceptionmessage = ex.Message;
                Response.Write("<script language=\"javascript\">alert(\""+exceptionmessage+"\");</script>");
            }
        }
        else if (IsPostBack) {

            this.gridViewTest.DataSource = dt;
            this.gridViewTest.DataBind();

        } else {
            Response.Write("<script language=\"javascript\">alert('You did not specify a file to import');</script>");

        }                                                 
    }


    protected override void Render(HtmlTextWriter writer)
    {
        for (int i = 0; i < gridViewTest.Rows.Count; i++)
            ClientScript.RegisterForEventValidation(gridViewTest.UniqueID, "Edit$" + i);
        base.Render(writer);
    }


    protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
    {

        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            string script = ClientScript.GetPostBackClientHyperlink(this.gridViewTest, "Edit$" + e.Row.RowIndex.ToString());
            e.Row.Attributes.Add("onclick", script);
        }

    }

   //xlApp.ActiveWorkbook.Signatures.AddSignatureLine();

    protected void gv_RowEditing(object sender, GridViewEditEventArgs e)
    {
        gridViewTest.EditIndex = e.NewEditIndex;
    }


    /// <summary>
    ///  Read Data from selected excel file on client
    /// </summary>
    /// <param name="filename">File Path</param>
    /// <returns></returns>
    private DataTable ReadExcelFile(string filename)
    {
        // Initializate an instance of DataTable
        dt = new DataTable();

        try
        {
            // Use SpreadSheetDocument class of Open XML SDK to open excel file
            using (SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Open(filename, false))
            {
                // Get Workbook Part of Spread Sheet Document
                WorkbookPart workbookPart = spreadsheetDocument.WorkbookPart;

                // Get all sheets in spread sheet document 
                IEnumerable<Sheet> sheetcollection = spreadsheetDocument.WorkbookPart.Workbook.GetFirstChild<Sheets>().Elements<Sheet>();

                // Get relationship Id
                string relationshipId = sheetcollection.First().Id.Value;

                // Get sheet1 Part of Spread Sheet Document
                WorksheetPart worksheetPart = (WorksheetPart)spreadsheetDocument.WorkbookPart.GetPartById(relationshipId);

                // Get Data in Excel file
                SheetData sheetData = worksheetPart.Worksheet.Elements<SheetData>().First();
                IEnumerable<Row> rowcollection = sheetData.Descendants<Row>();

                if (rowcollection.Count() == 0)
                {
                    return dt;
                }

                // Add columns
                foreach (Cell cell in rowcollection.ElementAt(0))
                {
                    dt.Columns.Add(GetValueOfCell(spreadsheetDocument, cell));
                }

                // Add rows into DataTable
                foreach (Row row in rowcollection)
                {
                    DataRow temprow = dt.NewRow();
                    for (int i = 0; i < row.Descendants<Cell>().Count(); i++)
                    {
                        temprow[i] = GetValueOfCell(spreadsheetDocument, row.Descendants<Cell>().ElementAt(i));
                    }

                    // Add the row to DataTable
                    // the rows include header row
                    dt.Rows.Add(temprow);
                }
            }

            // Here remove header row
            dt.Rows.RemoveAt(0);
            return dt;
        }
        catch(IOException ex)
        {
            throw new IOException(ex.Message);
        }
    }

    /// <summary>
    ///  Get Value in Cell 
    /// </summary>
    /// <param name="spreadsheetdocument">SpreadSheet Document</param>
    /// <param name="cell">Cell in SpreadSheet Document</param>
    /// <returns>The value in cell</returns>
    private static string GetValueOfCell(SpreadsheetDocument spreadsheetdocument, Cell cell)
    {
        // Get value in Cell
        SharedStringTablePart sharedString =spreadsheetdocument.WorkbookPart.SharedStringTablePart;
        if (cell.CellValue == null)
        {
            return string.Empty;
        }

        string cellValue = cell.CellValue.InnerText;

        // The condition that the Cell DataType is SharedString
        if (cell.DataType != null && cell.DataType.Value == CellValues.SharedString)
        {
            return sharedString.SharedStringTable.ChildElements[int.Parse(cellValue)].InnerText;
        }
        else
        {
            return cellValue;
        }
    }

    #endregion Import operation

    #region Export operation

    /// <summary>
    ///  Export Data in GridView control to Excel file
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnExport_Click(object sender, EventArgs e)
    {
        // Initialize an instance of DataTable
        DataTable dt = CreateDataTable(this.gridViewTest);

        // Save the exported file 
        string appPath = Request.PhysicalApplicationPath;
        string filename = Guid.NewGuid().ToString() + ".xlsx";
        string filePath = appPath+ filename;

        new CreateSpreadSheetProvider().ExportToExcel(dt, filePath);

        string savefilepath = "Export Excel file successfully, the exported excel file is placed in: " + filePath;
        Response.Write("<script language='javascript'>alert('"+savefilepath.Replace("\\","\\\\")+"');</script>");
    }

    /// <summary>
    ///  Create DataTable from GridView Control
    /// </summary>
    /// <param name="girdViewtest">GridView Control</param>
    /// <returns>An instance of DataTable Object</returns>
    private DataTable CreateDataTable(GridView girdViewtest)
    {
        dt = new DataTable();

        // Get columns from GridView
        // Add value of columns to DataTable 
        try
        {
            for (int i = 0; i < gridViewTest.HeaderRow.Cells.Count; i++)
            {
                dt.Columns.Add(gridViewTest.HeaderRow.Cells[i].Text);
            }
        }
        catch
        {
            throw;
        }


        // Get rows from GridView
        foreach (GridViewRow row in gridViewTest.Rows)
        {
            DataRow datarow = dt.NewRow();
            for (int i = 0; i < row.Cells.Count; i++)
            {
                datarow[i] = row.Cells[i].Text.Replace("&nbsp;", " ");
            }

            // Add rows to DataTable
            dt.Rows.Add(datarow);
        }

        return dt;
    }

    #endregion Export operation
}
4

3 回答 3

1

您需要在 RowEditing 事件中重新绑定 GridView。

在单击事件期间将该 DataTable 存储在 Session 变量中:

dt = ReadExcelFile(filename);
Session["userDataTable"] = dt;

然后使用它在行编辑时重新绑定您的 Gridview:

protected void gv_RowEditing(object sender, GridViewEditEventArgs e)
{
    gridViewTest.EditIndex = e.NewEditIndex;
    gridViewTest.DataSource = (DataTable)Session["userDataTable"];
    gridViewTest.DataBind();
}

由于您正在执行自定义数据绑定,因此您需要通过将编辑索引设置为单击的行来处理编辑事件,并且您需要确保所有数据仍然存在(通过重新绑定)。

于 2013-09-11T18:52:37.413 回答
1

鉴于您已经在使用自定义绑定,RowUpdated事件可能就是您正在寻找的。它提供的GridViewUpdatedEventArgs对象包括一个NewValues包含已编辑值的字典,然后您可以将其应用于基础数据源。

或者,您可以编写一个ObjectDataSource。正如他们所说,它允许您“将数据绑定到自定义业务对象”

于 2013-09-11T21:07:13.353 回答
0

您可能希望在绑定数据时检查行状态。发生的事情是 gridview 在每次回发时绑定数据(至少这是我的猜测)。因此,当您第一次绑定数据时,一切都很好,其中每行状态 = 正常或备用|正常。但是,当您单击编辑按钮时,会发生回发并触发“重新绑定”,仅当您选择的行将处于编辑模式或备用|编辑模式时。

尝试这个:

if (e.Row.RowState == DataControlRowState.Normal || e.Row.RowState == DataControlRoState.Alternate|DataControlRowState.Normal)
{
         if (e.Row.RowType == DataControlRowType.DataRow)
        {
            string script = ClientScript.GetPostBackClientHyperlink(this.gridViewTest,
             "Edit$" + e.Row.RowIndex.ToString());
            e.Row.Attributes.Add("onclick", script);
        }
}

因此,现在您的自定义处理将在行处于正常或备用|正常状态时触发。如果要处理行的编辑状态,请尝试:

 if (e.Row.RowState == DataControlRowState.Edit || e.Row.RowState == DataControlRoState.Alternate|DataControlRowState.Edit)
     {
        //your logic
     }
于 2013-12-04T17:37:17.520 回答