1

我正在开发一个网站,客户可以直接从我们的网站订购。直到几天前我更改了 GridView 的编辑方式时,我的代码才正常工作。我之前已将 GridView 设置为 AutoGenerate Columns,并更改了它,因为我需要更多的编辑功能功能。这是我创建表格的方式(当用户单击按钮以使用 GridView 添加快速详细信息时创建):

 public void CreateTable()
    {
        try
        {
            DataTable table = new DataTable();
            if (Session["table"] != null)
                table = (DataTable)Session["table"];
            else
            {
                table.Columns.Add("Part Number", typeof(string));
                table.Columns.Add("Quantity", typeof(Int32));
                table.Columns.Add("Ship-To", typeof(string));
                table.Columns.Add("Requested Date", typeof(string));
                table.Columns.Add("Shipping Method", typeof(string));
            }

            DataRow row = table.NewRow();
            row["Part Number"] = part;
            row["Quantity"] = qty;
            row["Ship-To"] = shipto;
            row["Requested Date"] = reqdate;
            row["Shipping Method"] = shipmthd;
            table.Rows.Add(row);

            Session["table"] = table;
            griditems.DataSource = table.DefaultView;
            griditems.DataBind();
        }
        catch
        {
            //error message
        }
    }

这将显示 Gridview 并允许用户根据他们的选择编辑/删除项目。然后我有另一个按钮,在创建 GridView 时显示,它实际上将 .csv 文件写入服务器(我的计算机暂时直到部署)。这是代码:

protected void orderbtn_Click(object sender, EventArgs e)
    {
        try
        {
            //ordernum++;
            //custordernum = ordernum.ToString("0000000");

            if (userlbl.Visible == false && userlbl2.Visible == false)
            {

                GlobalList.OnlineOrderNum.Add(custordernum, ordernum);
                FileStream fs = new FileStream(@"C:\Web_Order\Orders.Bin", FileMode.Create);
                BinaryFormatter bf = new BinaryFormatter();
                bf.Serialize(fs, GlobalList.OnlineOrderNum);
                fs.Close();
                fs.Dispose();

                ///Write CSV File For Order
                StringBuilder strBuilder = new StringBuilder();
                TextWriter tw = new StreamWriter(@"C:\Web_Order\Order_W" + custordernum.ToString() + ".csv");
                foreach (GridViewRow row in griditems.Rows)
                {
                    foreach (TableCell cell in row.Cells)
                    {
                        // get cell's text
                        string cellText = cell.Text;
                        // add quotes and comma around value and append
                        strBuilder.Append("\"" + cellText + "\",");
                    }
                    strBuilder.Append("\n");
                }
                // output CSV result
                tw.Write(strBuilder.ToString());
                tw.Close();
                tw.Dispose();
                GlobalList.weborder = "W" + custordernum.ToString();

                Response.Redirect("~/OrderSubmitted.aspx");
            }
            else
            {
                validatelbl.Text = "CANNOT SUBMIT FORM WITH ERRORS.  PLEASE CORRECT YOUR ERRORS BEFORE SUBMITTING.";
                validatelbl.Visible = true;
                userlbl.Text = "Please correct your table with the correct information before submitting your order";
                userlbl.Visible = true;
                userlbl2.Text = "Are your Part Numbers correct?  Are your Quantities in the correct format?";
                userlbl2.Visible = true;
            }
        }
        catch
        {
            //error message
        }
    }

这是我对 GridView 的编辑/删除代码:

protected void griditems_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        griditems.PageIndex = e.NewPageIndex;
        BindData();
    }

    protected void griditems_RowEditing(object sender, GridViewEditEventArgs e)
    {
        //Set the edit index. 
        griditems.EditIndex = e.NewEditIndex;

        //Bind data to the GridView control. 
        BindData();
    }

    protected void griditems_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        //Reset the edit index.
        griditems.EditIndex = -1;
        //Bind data to the GridView control.
        BindData();
    }

    protected void griditems_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        string valtext = "An error has occured, please check and make sure your editing is in the correct format and try again.";
        orderbtn.Visible = false;
        try
        {
            TextBox editpart = (TextBox)griditems.Rows[e.RowIndex].FindControl("partedit");      
            TextBox editqty = (TextBox)griditems.Rows[e.RowIndex].FindControl("qtyedit");
            TextBox editshipto = (TextBox)griditems.Rows[e.RowIndex].FindControl("shiptoedit");
            System.Web.UI.WebControls.Calendar editcal = (System.Web.UI.WebControls.Calendar)griditems.Rows[e.RowIndex].FindControl("reqdatecaledit"); 
            DropDownList editshipmthd = (DropDownList)griditems.Rows[e.RowIndex].FindControl("shipmthdedit"); 
            string newpart = editpart.Text.ToString();
            int newqty = Convert.ToInt32(editqty.Text);
            string newshipto = editshipto.Text.ToString();
            string newreqdate = editcal.SelectedDate.ToShortDateString();
            string newshipmthd = editshipmthd.SelectedItem.ToString();

            //Reset date if calendar date is not changed so it is not null!
            if (newreqdate == "1/1/0001")
                newreqdate = reqdate;

            DataTable dt = (DataTable)Session["table"]; 

            DataRow dr = dt.Rows[e.RowIndex];
            dr["Part Number"] = newpart;
            dr["Quantity"] = newqty;
            dr["Ship-TO"] = newshipto;
            dr["Requested Date"] = newreqdate;
            dr["Shipping Method"] = newshipmthd;                
            dr.AcceptChanges();

            Session["table"] = dt;

            if (validatelbl.Text == valtext)
                validatelbl.Visible = false;

            griditems.EditIndex = -1;
            BindData();
            orderbtn.Visible = true;
        }
        catch
        {                
            validatelbl.Text = valtext;
            validatelbl.Visible = true;
        }
    }

    protected void griditems_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        try
        {
            //DataTable dt = table;
            DataTable dt = (DataTable)Session["table"];
            if (dt.Rows.Count > 0)
            {
                dt.Rows.RemoveAt(e.RowIndex + griditems.PageIndex * 10);
                griditems.DataSource = dt;
                BindData();
            }
        }
        catch
        {
            validatelbl.Text = "An error occured while processing your request deleting a record.  Please try again.";
            validatelbl.Visible = true;
        }
    }

这是gridview的aspx代码:

<asp:GridView ID="griditems" runat="server" 
        onrowdeleting="griditems_RowDeleting" onrowediting="griditems_RowEditing" onrowupdating="griditems_RowUpdating"
                  AllowPaging="True" 
        onpageindexchanging="griditems_PageIndexChanging" Onrowcancelingedit="griditems_RowCancelingEdit" 
                  Caption="Order Details" AutoGenerateDeleteButton="True" 
        AutoGenerateEditButton="True" 
        AutoGenerateColumns="False" >            
        <EditRowStyle BackColor="#FF9900" BorderStyle="Double"/> 
        <HeaderStyle Font-Bold="True" Font-Italic="False" />
        <RowStyle HorizontalAlign="Center"/>
        <Columns> 
          <asp:TemplateField HeaderText="Part Number">
            <ItemTemplate>
              <asp:Label ID = "partlbl" runat="server" Text='<%#Eval("Part Number") %>'></asp:Label> 
            </ItemTemplate>
            <EditItemTemplate>
               <asp:TextBox ID="partedit" runat="server" Text='<%# Eval("Part Number")%>'  ></asp:TextBox>
            </EditItemTemplate>
          </asp:TemplateField>
          <asp:TemplateField HeaderText="Quantity">
            <ItemTemplate>
              <asp:Label ID = "qtylbl" runat="server" Text='<%#Eval("Quantity") %>'></asp:Label> 
            </ItemTemplate>
            <EditItemTemplate>
               <asp:TextBox ID="qtyedit" runat="server" Text='<%# Eval("Quantity")%>'  ></asp:TextBox>
            </EditItemTemplate>
          </asp:TemplateField>
          <asp:TemplateField HeaderText="Ship-To">
            <ItemTemplate>
              <asp:Label ID = "shiptolbl" runat="server" Text='<%#Eval("Ship-To") %>'></asp:Label> 
            </ItemTemplate>
            <EditItemTemplate>
               <asp:TextBox ID="shiptoedit" runat="server" Text='<%# Eval("Ship-To")%>'  ></asp:TextBox>
            </EditItemTemplate>
          </asp:TemplateField>
          <asp:TemplateField HeaderText="Requested Date">
            <ItemTemplate>
              <asp:Label ID = "reqdatelbl" runat="server" Text='<%#Eval("Requested Date") %>'></asp:Label> 
            </ItemTemplate>
            <EditItemTemplate>
                <asp:Calendar ID="reqdatecaledit" runat="server" BackColor="White" BorderColor="#3366CC" BorderWidth="1px" CellPadding="1" 
                              DayNameFormat="Shortest" Font-Names="Verdana" Font-Size="8pt" ForeColor="#003399" Height="200px" Width="220px" 
                              ondayrender="reqdatecal_DayRender" ShowGridLines="True">
                              <DayHeaderStyle BackColor="#99CCCC" ForeColor="#336666" Height="1px" />
                              <DayStyle BackColor="White" />
                              <NextPrevStyle Font-Size="8pt" ForeColor="#CCCCFF" />
                              <OtherMonthDayStyle ForeColor="#999999" />
                              <SelectedDayStyle BackColor="#FF9900" Font-Bold="True" ForeColor="#CCFF99" />
                              <SelectorStyle BackColor="#99CCCC" ForeColor="#336666" />
                              <TitleStyle BackColor="#003399" BorderColor="#3366CC" BorderWidth="1px" Font-Bold="True" Font-Size="10pt" ForeColor="#CCCCFF" 
                                          Height="25px" />
                              <TodayDayStyle BackColor="#99CCCC" ForeColor="White" />
                              <WeekendDayStyle BackColor="#CCCCFF" /></asp:Calendar>
            </EditItemTemplate>
          </asp:TemplateField>
          <asp:TemplateField HeaderText="Shipping Method">  
            <ItemTemplate><asp:Label ID="shipmthdlbl" runat="server" Text='<%#Eval("Shipping Method") %>'></asp:Label>   
            </ItemTemplate>              
              <EditItemTemplate>            
                <asp:DropDownList ID="shipmthdedit" runat="server">                
                  <asp:ListItem>FedEx Ground (1-5 Business Days)</asp:ListItem>
                  <asp:ListItem>FedEx 3 Business Days</asp:ListItem>
                  <asp:ListItem>FedEx 2 Business Days</asp:ListItem>
                  <asp:ListItem>FedEx Overnight</asp:ListItem>   
                </asp:DropDownList>    
              </EditItemTemplate>  
            </asp:TemplateField>    
        </Columns>    
    </asp:GridView>

我不明白为什么它一直在工作,而现在突然间它不起作用了。它使用新的订单号创建文件,它只是 .csv 文件是空的(根本没有数据)有什么想法吗?

4

2 回答 2

0

您可以更正路径,并将 TextWriter 替换为 StreamWriter

var path = Path.Combine("C:\Web_Order\Order_W",custordernum.ToString(),".csv");
StreamWriter tw = new StreamWriter(@path);

或者直接使用var。

var tw = new StreamWriter(@path);

使用 try catch 块调整您的代码,以便在发生异常时处理异常

try
{

}
catch(Exception ex)
{
  Console.Write(ex.Message); 
  throw ex;
}
于 2012-08-30T14:07:09.260 回答
0

不知道你为什么在TextWriter这里使用,你不需要重定向。写信给Response.Write().

protected void btnDownload_Click(object sender, EventArgs e)
{
    // No error so write as attachment
    Response.ContentType = "text/csv";
    Response.AddHeader("content-disposition", "attachment;filename=data.csv");

    // Write your output here
    Response.Write(...);

    Response.End();
}
于 2012-08-30T18:44:00.960 回答