【问题标题】:Exported gridview to csv is empty导出到 csv 的 gridview 为空
【发布时间】:2014-02-25 13:19:53
【问题描述】:

我想通过单击“RunSimulationButton”按钮将我的 Gridview 导出到 csv 文件。但是,我当前的代码似乎只导出列名,而不导出gridview的单元格内容。

任何帮助将不胜感激!谢谢! (P.S:我是 ASP.NET 的初学者)

这是我的代码:

ASPX

<asp:GridView ID="InflationGridView" runat="server" AutoGenerateColumns="False" Width="52%"
                                            ShowHeaderWhenEmpty="True" CellPadding="4" ForeColor="#333333" GridLines="None"
                                            AllowSorting="True" ShowFooter="True">
                                            <AlternatingRowStyle BackColor="White" ForeColor="#284775" Height="2px" />
                                            <Columns>
                                                <asp:TemplateField HeaderText="Start Year">
                                                    <ItemStyle Font-Size="13px" Width="20%" HorizontalAlign="Center" />
                                                    <ItemTemplate>
                                                        <asp:TextBox ID="StartInflationTextBox" runat="server" Width="60px" Text="" Style="text-align: center;"></asp:TextBox>
                                                        <asp:NumericUpDownExtender ID="StartInflationNumericUpDownExtender" runat="server"
                                                            TargetControlID="StartInflationTextBox" Minimum="0" Width="60">
                                                        </asp:NumericUpDownExtender>
                                                    </ItemTemplate>
                                                </asp:TemplateField>
                                                <asp:TemplateField HeaderText="End Year">
                                                    <ItemStyle Font-Size="13px" Width="20%" HorizontalAlign="Center" />
                                                    <ItemTemplate>
                                                        <asp:TextBox ID="EndInflationTextBox" runat="server" Width="60px" Text="" Style="text-align: center;"></asp:TextBox>
                                                        <asp:NumericUpDownExtender ID="EndInflationNumericUpDownExtender" runat="server"
                                                            TargetControlID="EndInflationTextBox" Minimum="1" Width="60">
                                                        </asp:NumericUpDownExtender>
                                                    </ItemTemplate>
                                                </asp:TemplateField>
                                                <asp:TemplateField HeaderText="Inflation Rate">
                                                    <ItemStyle Font-Size="13px" Width="25%" HorizontalAlign="Center" Height="2px" />
                                                    <ItemTemplate>
                                                        <asp:TextBox ID="InflationTextBox" runat="server" Text="" Width="60px" Style="text-align: center;"></asp:TextBox>
                                                        %
                                                    </ItemTemplate>
                                                    <FooterStyle HorizontalAlign="Right" />
                                                    <FooterTemplate>
                                                        <asp:Button ID="AddNewInflationRowButton" runat="server" Text="Add New Row" OnClick="AddNewInflationRowButton_Click"
                                                            Height="25px" />
                                                    </FooterTemplate>
                                                </asp:TemplateField>
                                            </Columns>
                                            <FooterStyle Font-Bold="True" ForeColor="White" Height="20px" />
                                            <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                                            <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
                                            <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
                                            <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" Height="10px" />
                                            <SortedAscendingCellStyle BackColor="#E9E7E2" />
                                            <SortedAscendingHeaderStyle BackColor="#506C8C" />
                                            <SortedDescendingCellStyle BackColor="#FFFDF8" />
                                            <SortedDescendingHeaderStyle BackColor="#6F8DAE" />
                                        </asp:GridView>
<asp:Button ID="RunSimulationButton" runat="server" Text="Run Simulation" OnClick="RunSimulationButton_OnClick" />

ASPX.cs

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            FirstInflationGridViewRow();
        }


    }


    // Display first row of the GridView
    protected void FirstInflationGridViewRow()
    {
        DataTable table = new DataTable();
        DataRow dr = null;

        table.Columns.Add(new DataColumn("Col1", typeof(int)));
        table.Columns.Add(new DataColumn("Col2", typeof(int)));
        table.Columns.Add(new DataColumn("Col3", typeof(double)));

        dr = table.NewRow();

        dr["Col1"] = DBNull.Value;
        dr["Col2"] = DBNull.Value;
        dr["Col3"] = DBNull.Value;

        table.Rows.Add(dr);

        ViewState["currentInflationTable"] = table;
        InflationGridView.DataSource = table;
        InflationGridView.DataBind();
    }



    // Button to add rows to the GridView
    protected void AddNewInflationRowButton_Click(object sender, EventArgs e)
    {
        AddNewInflationRow();
    }

    private void AddNewInflationRow()
    {
        int rowIndex = 0;

        if (ViewState["currentInflationTable"] != null)
        {
            DataTable dtCurrentTable = (DataTable)ViewState["currentInflationTable"];
            DataRow drCurrentRow = null;
            if (dtCurrentTable.Rows.Count > 0)
            {
                for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
                {
                    TextBox TextBoxStart =
                      (TextBox)InflationGridView.Rows[rowIndex].Cells[0].FindControl("StartInflationTextBox");
                    TextBox TextBoxEnd =
                      (TextBox)InflationGridView.Rows[rowIndex].Cells[1].FindControl("EndInflationTextBox");
                    TextBox TextBoxInflation =
                      (TextBox)InflationGridView.Rows[rowIndex].Cells[2].FindControl("InflationTextBox");

                    drCurrentRow = dtCurrentTable.NewRow();

                    int Num;
                    bool isNumStart = String.IsNullOrEmpty(TextBoxStart.Text.ToString()) ? true : int.TryParse(TextBoxStart.Text.ToString(), out Num);
                    bool isNumEnd = String.IsNullOrEmpty(TextBoxEnd.Text.ToString()) ? true : int.TryParse(TextBoxEnd.Text.ToString(), out Num);
                    bool isNumInflation = String.IsNullOrEmpty(TextBoxInflation.Text.ToString()) ? true : int.TryParse(TextBoxInflation.Text.ToString(), out Num);

                    if (!isNumStart || !isNumEnd || !isNumInflation)
                    {
                        this.ErrorInflationLabel.Text = "Incorrect input(s). All fields must be numeric.";
                        ErrorInflationLabel.ForeColor = System.Drawing.Color.Red;
                        this.ErrorInflationLabel.Visible = true;
                        this.InflationErrorUpdatePanel.Update();
                        return;

                    }
                    else if ((TextBoxStart.Text == "") || (TextBoxEnd.Text == "") || (TextBoxInflation.Text == ""))
                    {
                        this.ErrorInflationLabel.Text = "All fields must be completed.";
                        ErrorInflationLabel.ForeColor = System.Drawing.Color.Red;
                        this.ErrorInflationLabel.Visible = true;
                        this.InflationErrorUpdatePanel.Update();
                        return;

                    }
                    else if (TextBoxEnd.Text == HorizonTextBox.Text)
                    {
                        this.ErrorInflationLabel.Text = "Cannot set inputs beyond investment horizon.";
                        ErrorInflationLabel.ForeColor = System.Drawing.Color.Red;
                        this.ErrorInflationLabel.Visible = true;
                        this.InflationErrorUpdatePanel.Update();
                        return;
                    }
                    else
                    {
                        this.ErrorInflationLabel.Text = "";
                        this.InflationErrorUpdatePanel.Update();
                        dtCurrentTable.Rows[i - 1]["Col1"] = TextBoxStart.Text;
                        dtCurrentTable.Rows[i - 1]["Col2"] = TextBoxEnd.Text;
                        dtCurrentTable.Rows[i - 1]["Col3"] = TextBoxInflation.Text;                           
                        rowIndex++;
                    }
                }


                dtCurrentTable.Rows.Add(drCurrentRow);
                dtCurrentTable.Rows[dtCurrentTable.Rows.Count - 1]["Col1"] = (Convert.ToDouble(dtCurrentTable.Rows[dtCurrentTable.Rows.Count - 2]["Col2"]) + 1).ToString();
                dtCurrentTable.Rows[dtCurrentTable.Rows.Count - 1]["Col2"] = HorizonTextBox.Text;

                ViewState["currentInflationTable"] = dtCurrentTable;

                InflationGridView.DataSource = dtCurrentTable;
                InflationGridView.DataBind();
            }
        }
        else
        {
            Response.Write("ViewState is null");
        }
        SetPreviousInflationData();
    }

    // Set data in previous rows when new row is added
    private void SetPreviousInflationData()
    {
        int rowIndex = 0;
        if (ViewState["currentInflationTable"] != null)
        {
            DataTable dt = (DataTable)ViewState["currentInflationTable"];
            if (dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    TextBox TextBoxStart = (TextBox)InflationGridView.Rows[rowIndex].Cells[0].FindControl("StartInflationTextBox");
                    TextBox TextBoxEnd = (TextBox)InflationGridView.Rows[rowIndex].Cells[1].FindControl("EndInflationTextBox");
                    TextBox TextBoxInflation =
                      (TextBox)InflationGridView.Rows[rowIndex].Cells[2].FindControl("InflationTextBox");

                    TextBoxStart.Text = dt.Rows[i]["Col1"].ToString();
                    TextBoxEnd.Text = dt.Rows[i]["Col2"].ToString();
                    TextBoxInflation.Text = dt.Rows[i]["Col3"].ToString();
                    rowIndex++;
                }
            }
        }
    }


 //************************* EXPORT TO CSV BY CLICKING ON SIMULATION BUTTON

    protected void retrieveInflationData()
    {
        if (Session["currentInflationTable"] != null)
        {
            DataTable dt = (DataTable)Session["currentInflationTable"]; ;

            if ((dt != null) && (dt.Rows.Count > 0))
            {
                InflationGridView.Visible = true;
                InflationGridView.DataSource = dt;
                InflationGridView.DataBind();
            }
            else
            {
                InflationGridView.Visible = false;
            }
        }
    }

    protected void RunSimulationButton_OnClick(object sender, EventArgs e)
    {
        retrieveInflationData();
        StreamWriter sw = new StreamWriter("C:\inst_research\MonteCarlo\gridview.csv");
        // now add the gridview header in csv file suffix with "," delimeter except last one
        for (int i = 0; i < InflationGridView.Columns.Count; i++)
        {
            sw.Write(InflationGridView.Columns[i].HeaderText);
            if (i != InflationGridView.Columns.Count)
            {
                sw.Write(",");
            }
        }
        // add new line
        sw.Write(sw.NewLine);
        // iterate through all the rows within the gridview
        foreach (GridViewRow dr in InflationGridView.Rows)
        {
            // iterate through all colums of specific row
            for (int i = 0; i < InflationGridView.Columns.Count; i++)
            {
                // write particular cell to csv file
                string test = dr.Cells[i].Text;
                sw.Write(dr.Cells[i].Text);
                if (i != InflationGridView.Columns.Count)
                {
                    sw.Write(",");
                }
            }
            // write new line
            sw.Write(sw.NewLine);
        }
        // flush from the buffers.
        sw.Flush();
        // closes the file
        sw.Close();
    }

【问题讨论】:

  • Mariam,这里的人很懒,尽量把问题本地化,把问题缩短..
  • 我不确定您所说的本地化是什么意思。如果我不发布有效的(完整)代码,人们会抱怨我的示例不可重现......
  • 你调试过你的代码吗?这条线有效吗? foreach (GridViewRow dr in InflationGridView.Rows) { // 遍历特定行的所有列 for (int i = 0; i
  • 是的,它可以完美调试。但是由于某种原因,数据没有被写入文件。为了查看我是否真的读取了gridview数据,我在循环中引入了测试字符串string test = dr.Cells[i].Text,在调试期间,测试采用了正确的值..
  • 当你调试时,它从哪一行开始做有趣的事情?如果这是一个权限问题,你会得到一个异常,那么它不会遍历你的 gridviewrows 吗?换句话说,您从不共享的窃听中学到了什么?

标签: c# asp.net .net csv gridview


【解决方案1】:

自己解决了这个问题。由于 GridView 包含 TemplateFields 而不是 BoundFields,因此应该这样做:

       StreamWriter sw = new StreamWriter("C:\inst_research\MonteCarlo\gridview.csv");
       foreach (GridViewRow row in InflationGridView.Rows)
        {

            foreach (TableCell cell in row.Cells)
            {
                string text = "";
                if (cell.Controls.Count > 0)
                {
                    foreach (Control control in cell.Controls)
                    {
                        switch (control.GetType().Name)
                        {
                            case "TextBox":
                                text = (control as TextBox).Text;
                                break;
                            case "DropDownList":
                                text = (control as DropDownList).SelectedItem.Text;
                                break;
                        }
                    }
                }
                else
                {
                    text = cell.Text;
                }
                sw.Write(text + ',');
            }
            sw.Write("\r\n");

        }

【讨论】:

    【解决方案2】:
        Response.Clear();
    
        Response.Buffer = true;
    
        Response.AddHeader("content-disposition",
    
         "attachment;filename=GridViewExport.csv");
    
        Response.Charset = "";
    
        Response.ContentType = "application/text";
        DataTable dt = new DataTable();
        string cn =      System.Configuration.ConfigurationManager.ConnectionStrings["Myconnection"].ConnectionString;
        SqlConnection con = new SqlConnection(cn);
        SqlCommand cmd = new SqlCommand("select a.Emp_Id,a.Emp_F_name,a.Emp_L_name,b.Dept_Name,a.Emp_dob,a.IsDeleted from Employee_tbl a Inner join Department_tbl b on a.Dept_Id=b.Dept_Id where a.IsDeleted='true'", con);
        con.Open();
        SqlDataAdapter adp = new SqlDataAdapter();
        DataSet dset = new DataSet();
        adp.SelectCommand = cmd;
        adp.Fill(dset);
        Gridview1.DataSource = dset.Tables[0];
        Gridview1.DataBind();
        Gridview1.AllowPaging = false;
        StringBuilder sb = new StringBuilder();
    
    
        int m;
        for (m = 0; m < Gridview1.Columns.Count; m++)
        {
    
            //add separator
    
            sb.Append(Gridview1.Columns[m].HeaderText+',' );
    
        }
        sb.Append("\r\n");
            for (int i = 0; i < Gridview1.Rows.Count; i++)
            {
                Label tt = Gridview1.Rows[i].FindControl("lblname") as Label;
                sb.Append(tt.Text + ',');
                tt = Gridview1.Rows[i].FindControl("Label4") as Label;
                sb.Append(tt.Text + ',');
                tt = Gridview1.Rows[i].FindControl("Label5") as Label;
                sb.Append(tt.Text );
                sb.Append("\r\n");
            }
    
        Response.Output.Write(sb.ToString());
    
        Response.Flush();
    
        Response.End();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-12-20
      • 1970-01-01
      • 2011-10-04
      • 2023-01-20
      • 2023-03-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多