【问题标题】:Gridview edit/delete problemsGridview 编辑/删除问题
【发布时间】:2012-08-20 17:20:18
【问题描述】:

我有一个网格视图,它显示在线订单的一些基本信息(零件、数量、发货地址、请求日期和发货方式)。当我在网格视图中选择“编辑”或“删除”链接时,出于某种原因,它不会让我做任何一个。这是我所拥有的:

protected void Page_Load(object sender, EventArgs e)
    {                          
        table = new DataTable("myTable");
        DataColumn column1 = new DataColumn();
        column1.DataType = typeof(string);
        column1.ColumnName = "Part";
        DataColumn column2 = new DataColumn();
        column2.DataType = typeof(Int32);
        column2.ColumnName = "Quantity";
        DataColumn column3 = new DataColumn();
        column3.DataType = typeof(string);
        column3.ColumnName = "Ship-To";
        DataColumn column4 = new DataColumn();
        column4.DataType = typeof(string);
        column4.ColumnName = "Requested Date";
        DataColumn column5 = new DataColumn();
        column5.DataType = typeof(string);
        column5.ColumnName = "Shipping Method";
        table.Columns.Add(column1);
        table.Columns.Add(column2);
        table.Columns.Add(column3);
        table.Columns.Add(column4);
        table.Columns.Add(column5);
     }

    protected void addbtn_Click(object sender, EventArgs e)
    {
        //assign all variables in form
        part = parttxtbox.Text.ToUpper();
        shipto = shiptotxtbox.Text;
        reqdate = reqdatecal.SelectedDate.ToShortDateString();
        shipmthd = shipddl.SelectedItem.ToString();
        //validate to make sure all fields are in correct format and acceptable for processing
        if ((importlstbx.Items.Contains(item)) && (qtychk == 1) && (shipto.ToString() != "") &&
            (Convert.ToDateTime(reqdate) >= DateTime.Today) && (shipmthd != "-- Select --"))
        {
            validatelbl.Visible = false;
            Session["Part"] += part + "|";
            Session["Quantity"] += qty + "|";
            Session["Ship-To"] += shipto + "|";
            Session["Requested Date"] += reqdate + "|";
            Session["Shipping Method"] += shipddl.SelectedItem.ToString() + "|";
            CreateTable();

            //Clear All Data on Postback
            ClearTextBoxes(Page);
            //ClearDDLBoxes(Page);  
            SetFocus(parttxtbox);
        }
        orderbtn.Visible = true;
    }

    public void CreateTable()
    {
        string[] spart = Session["Part"].ToString().Split('|');
        string[] sqty = Session["Quantity"].ToString().Split('|');
        string[] sship = Session["Ship-To"].ToString().Split('|');
        string[] sdate = Session["Requested Date"].ToString().Split('|');
        string[] smethod = Session["Shipping Method"].ToString().Split('|');
        int recordnum = spart.Length;

        for (int i = 0; i < recordnum - 1; i++)
        {
            DataRow row = table.NewRow();
            row["Part"] = spart[i].ToString();
            row["Quantity"] = sqty[i].ToString();
            row["Ship-To"] = sship[i].ToString();
            row["Requested Date"] = sdate[i].ToString();
            row["Shipping Method"] = smethod[i].ToString();
            table.Rows.Add(row);
        }
        griditems.DataSource = table.DefaultView;
        griditems.DataBind();
    }

    private void BindData()
    {
        griditems.DataSource = table;
        griditems.DataBind();
    }

    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)
    {
        //Retrieve the table from the session object.
        DataTable dt = table;

        //Update the values.
        GridViewRow row = griditems.Rows[e.RowIndex];
        dt.Rows[row.DataItemIndex]["Part"] = ((TextBox)(row.Cells[1].Controls[0])).Text;
        dt.Rows[row.DataItemIndex]["Quantity"] = ((TextBox)(row.Cells[2].Controls[0])).Text;
        dt.Rows[row.DataItemIndex]["Ship-To"] = ((TextBox)(row.Cells[3].Controls[0])).Text;
        dt.Rows[row.DataItemIndex]["Requested Date"] = ((TextBox)(row.Cells[4].Controls[0])).Text;
        dt.Rows[row.DataItemIndex]["Shipping Method"] = ((DropDownList)(row.Cells[5].Controls[0])).SelectedItem;

        //Reset the edit index.
        griditems.EditIndex = -1;
        //Bind data to the GridView control.
        BindData();
    }

    protected void griditems_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        //int id = Convert.ToInt32(griditems.DataKeys[e.RowIndex].Values[0].ToString());
        //griditems.DeleteRow(id);
        //BindData();


        //string item = griditems.DataKeys[e.RowIndex].Value.ToString();
        //griditems.DeleteRow(Convert.ToInt32(item));
        //BindData();

        //TextBox FileContentsTextBox = parttxtbox.FindControl("part") as TextBox;
        //FileContentsTextBox.Text = string.Format("You have opted to delete {0}.", item);
        //File.Delete(item);

        //////((DataTable)ViewState["Data"]).Rows.RemoveAt(e.RowIndex);
        //((DataTable)table).Rows.RemoveAt(e.RowIndex);
        //BindData();
        ////griditems.DataSource = ((DataTable)table);
        ////griditems.DataBind();

    }

}

我尝试了很多东西,这就是为什么这么多被注释掉的原因。不用说,它没有用。

【问题讨论】:

  • 点击其中一个链接会发生什么?
  • 当我点击编辑时,gridview 会消失,直到我再次填写表单,然后它会显示编辑详细信息以进行编辑,但是当我点击更新时会崩溃。当我点击删除链接时,它似乎只是回发而不是其他任何事情(这很有意义,因为所有内容都被注释掉了,但后来我取消了上面前 3 行的注释: int id = Convert.ToInt32(griditems.DataKeys[e .RowIndex].Values[0].ToString()); griditems.DeleteRow(id); BindData(); 我得到指向第一行的索引超出范围错误

标签: c# asp.net gridview


【解决方案1】:

您必须将 ViewState 添加到您的网格中并且只绑定一次(发布时您不会重新创建表格)

If(! IsPostBack)
{
     //Create table

     table = new DataTable("myTable");
        DataColumn column1 = new DataColumn();
        column1.DataType = typeof(string);
        column1.ColumnName = "Part";
        DataColumn column2 = new DataColumn();
        column2.DataType = typeof(Int32);
        column2.ColumnName = "Quantity";
        DataColumn column3 = new DataColumn();
        column3.DataType = typeof(string);
        column3.ColumnName = "Ship-To";
        DataColumn column4 = new DataColumn();
        column4.DataType = typeof(string);
        column4.ColumnName = "Requested Date";
        DataColumn column5 = new DataColumn();
        column5.DataType = typeof(string);
        column5.ColumnName = "Shipping Method";
        table.Columns.Add(column1);
        table.Columns.Add(column2);
        table.Columns.Add(column3);
        table.Columns.Add(column4);
        table.Columns.Add(column5);

}

2 将 ViewState 添加到您的 gridView

【讨论】:

    【解决方案2】:
    protected void Page_Load(object sender, EventArgs e)
        {
           if (!Page.IsPostBack)
           {
            //Bind gridview
           }
         }
    

    http://satindersinght.blogspot.in/2012/08/how-to-addupdate-record-using-gridview.html

    【讨论】:

      【解决方案3】:

      我终于找到了问题的答案。这是允许我在绑定到 DataTable 时删除所选行的代码。

      protected void griditems_RowDeleting(object sender, GridViewDeleteEventArgs e)
          {
              DataTable dt = table;
              if (dt.Rows.Count > 0)
              {
                  dt.Rows.RemoveAt(e.RowIndex);
                  griditems.DataSource = dt;
                  BindData();
              } 
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-02-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多