如何在asp.net中的临时表数据表中添加行

时间:2014-06-21 20:09:21

标签: asp.net datatable viewstate

protected void Add_New_Click(object sender, System.EventArgs e)
        {



            DataTable dt= new DataTable();

            DataRow dr;
            dr = dt.NewRow();


            string CustomerID = ((TextBox)GridView1.FooterRow.FindControl("txtCustomerID")).Text;
            string CustomerName = ((TextBox)GridView1.FooterRow.FindControl("txtCustomerName")).Text;
            string CustomerFatherName = ((TextBox)GridView1.FooterRow.FindControl("txtCustomerFatherName")).Text;
            dt.Rows.Add(dr);
            GridView1.DataSource = dt;
            GridView1.DataBind();
            ViewState["sajjad_Viewstate"] = dt;


        }

2 个答案:

答案 0 :(得分:0)

试试这个:

protected void Add_New_Click(object sender, System.EventArgs e)
        {



            DataTable dt= new DataTable();
         // Add columns here
            dt.Columns.Add(new DataColumn("CustomerID"));
            dt.Columns.Add(new DataColumn("CustomerName"));
            dt.Columns.Add(new DataColumn("CustomerFatherName"));
            //Create new row
            DataRow dr= dt.NewRow();


            string CustomerID = ((TextBox)GridView1.FooterRow.FindControl("txtCustomerID")).Text;
            string CustomerName = ((TextBox)GridView1.FooterRow.FindControl("txtCustomerName")).Text;
            string CustomerFatherName = ((TextBox)GridView1.FooterRow.FindControl("txtCustomerFatherName")).Text;
            //populate columns with data

            dr["CustomerID"] = CustomerID;
            dr["CustomerID"] = CustomerName;
            dr["CustomerFatherName"] = CustomerFatherName;

            dt.Rows.Add(dr);
            GridView1.DataSource = dt;
            GridView1.DataBind();
            ViewState["sajjad_Viewstate"] = dt;


        }

答案 1 :(得分:0)

        dt.Columns.Add("ItemName", typeof(string));
        dt.Columns.Add("ItemCode", typeof(string));
        dt.Columns.Add("Price", typeof(decimal));
        dt.Columns.Add("Qty", typeof(decimal));
        dt.Columns.Add("Amount", typeof(decimal));
        dr = dt.NewRow();
        dr[0] = txtitemname.Text;
        dr[1] = txtitemcode.Text;
        dr[2] = Convert.ToDecimal(txtprice.Text);
        dr[3] = Convert.ToDecimal(txtqty.Text);
        dr[4] = Convert.ToDecimal(txtamount.Text);
        dt.Rows.Add(dr);
        dt.AcceptChanges();
        ViewState["DtItem"] = dt;
    }
    else
    {
        dt = (DataTable)ViewState["DtItem"];
        dr = dt.NewRow();
        dr[0] = txtitemname.Text;
        dr[1] = txtitemcode.Text;
        dr[2] = Convert.ToDecimal(txtprice.Text);
        dr[3] = Convert.ToDecimal(txtqty.Text);
        dr[4] = Convert.ToDecimal(txtamount.Text);
        dt.Rows.Add(dr);
        dt.AcceptChanges();
        ViewState["DtItem"] = dt;
    }
    grditem.DataSource =(DataTable)ViewState["DtItem"];