日期:2014-05-18  浏览次数:20378 次

ASP.NET GridView行的添加删除不涉及数据库
Microsoft JScript 运行时错误: Sys.WebForms.PageRequestManagerServerErrorException: 在位置 0 处没有任何行。

以上是错误提示,下面是后台代码:

public partial class WebForm3 : System.Web.UI.Page
  {
  public static DataTable Cpdt;
  protected void Page_Load(object sender, EventArgs e)
  {
  Createbt();
  if (!IsPostBack)
  {
  GridView1.DataSource = Cpdt;
  GridView1.DataBind();
  }
  }

  void Createbt()
  {
  Cpdt = new DataTable();
  DataColumn mycol = new DataColumn();
  Cpdt.Columns.Add(new DataColumn("CPID",typeof(Int32)));
  Cpdt.Columns.Add(new DataColumn("CPNAME",typeof(String)));
  Cpdt.Columns.Add(new DataColumn("CPDJ", typeof(Single)));
  Cpdt.Columns.Add(new DataColumn("SL", typeof(Int32)));
  Cpdt.Columns.Add(new DataColumn("CPSUM", typeof(Double)));
  Cpdt.AcceptChanges();
  Cpdt.PrimaryKey = new DataColumn[] { Cpdt.Columns[1] };
  Cpdt.AcceptChanges();
  }

  protected void Button1_Click(object sender, EventArgs e)
  {
  DataRow myrow = Cpdt.NewRow();
  myrow[0] = TextBox1.Text;
  myrow[1] = TextBox2.Text;
  myrow[2] =Convert.ToSingle(TextBox3.Text);
  myrow[3] = TextBox4.Text;
  Cpdt.Rows.Add(myrow);
  var mm=Cpdt.AsEnumerable().Sum(p=>Convert.ToDouble( p["SL"]));
  Label3.Text = mm.ToString();
  Cpdt.AcceptChanges();
  GridView1.DataSource = Cpdt;
  GridView1.DataBind();
  }

  protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
  {
  int rowkey = e.RowIndex;
  Cpdt.Rows.RemoveAt(rowkey);
  Cpdt.AcceptChanges();
  GridView1.EditIndex = -1;
  GridView1.DataSource = Cpdt;
  GridView1.DataBind();

  // //Cpdt.Rows[e.RowIndex].Delete();
  // //GridView1.DataSource = Cpdt;
  // //GridView1.DataBind();
  // //当前点击删除行的行号
  }
  }


把前台的也贴上来吧,这小问题困了我好久了,郁闷死。


<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
  DataKeyNames="CPID"  
  onrowdeleting="GridView1_RowDeleting" 
  >
  <Columns>
  <asp:BoundField DataField="CPID" HeaderText="产品编号" ReadOnly="True" 
  SortExpression="CPID" />
  <asp:BoundField DataField="CPNAME" HeaderText="产品名" ReadOnly="True" 
  SortExpression="CPNAME" />
  <asp:BoundField DataField="CPDJ" HeaderText="产品单价" ReadOnly="True" 
  SortExpression="CPDJ" />
  <asp:TemplateField HeaderText="数量" SortExpression="S