【发布时间】: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