如何在按钮单击时在gridview中添加新行

时间:2014-06-24 11:10:38

标签: asp.net gridview ado.net

我是asp.net的新手,我想在按钮点击的gridview中添加新行...看到我的代码,请帮助我..我已经工作了2天但没有找到解决方案.... HTML CODE

<div>
    <asp:GridView ID="GridView1" runat="server" ShowFooter="true" AutoGenerateColumns="false"
        DataKeyNames="PRODUCTID" CellPadding="3" GridLines="Both" OnRowEditing="gridOnRowEditing"
        OnRowCancelingEdit="gridOnRowCancelingEdit" OnRowUpdating="gridOnRowUpdating">
        <HeaderStyle BackColor="Cyan" ForeColor="White" BorderColor="Red" />
        <Columns>
            <asp:CommandField ButtonType="Button" ShowCancelButton="true" ShowEditButton="true"
                HeaderText="Edit & Update" />
            <asp:BoundField DataField="PRODUCTID" HeaderText="PRODUCT ID" ReadOnly="true" />
            <asp:TemplateField HeaderText="PRODUCT NAME">
                <ItemTemplate>
                    <asp:TextBox runat="server" ID="txtProduct1" Text='<%# Eval("PRODUCTNAME") %>'></asp:TextBox>
                </ItemTemplate>
                <EditItemTemplate>
                    <asp:TextBox runat="server" ID="txtProduct" Text='<%# Eval("PRODUCTNAME") %>'></asp:TextBox>
                </EditItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="UNIT PRICE">
                <ItemTemplate>
                    <asp:TextBox runat="server" ID="txtPrice1" Text='<%# Eval("UNITPRICE") %>'></asp:TextBox>
                </ItemTemplate>
                <EditItemTemplate>
                    <asp:TextBox runat="server" ID="txtPrice" Text='<%# Eval("UNITPRICE") %>'></asp:TextBox>
                </EditItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>
    <asp:Button runat="server" OnClick="button1_click" ID="button1" Text="Add New Row" />
    <%--   <input type="button" id="btnNew" value="Add New" onclick="addNew()" />--%>
</div>

C SHARP CODE

    public partial class WebForm1 : System.Web.UI.Page
    {
        SqlConnection con = new SqlConnection("Data Source=localhost;Initial Catalog=practice;Integrated Security=true;");

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                BindData();
            }


        }

        protected void BindData()
        {
            SqlDataAdapter sda = new SqlDataAdapter("Select * From PRODUCTDETAILS order by PRODUCTID asc", con);
            DataTable dt = new DataTable();
            sda.Fill(dt);
            GridView1.DataSource = dt;
            GridView1.DataBind();
            ViewState["CurrentTable"] = dt;

        }
        protected void gridOnRowEditing(object sender, GridViewEditEventArgs e)
        {

           GridView1.EditIndex = e.NewEditIndex;
           BindData();

        }
        protected void gridOnRowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {

            GridView1.EditIndex = -1;
            BindData();
        }
        protected void gridOnRowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];

            TextBox txtProductName = (TextBox)row.FindControl("txtProduct");
            TextBox UNITPRICE = (TextBox)row.FindControl("txtPrice");

            string ProductName = txtProductName.Text;
            string txtUnitPrice = UNITPRICE.Text;
            int ProductID = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value);
            UpdateRecord(ProductID, ProductName, txtUnitPrice);
        }
        protected void UpdateRecord(int ProductID, string ProductName, string UnitPrice)
        {
            try
            {
                SqlCommand cmd = new SqlCommand("Update PRODUCTDETAILS set ProductName=@ProductName,UnitPrice=@UnitPrice WHERE ProductID=@ProductID", con);

                cmd.Parameters.Add(new SqlParameter("@ProductID", ProductID));
                cmd.Parameters.Add(new SqlParameter("@ProductName", ProductName));
                cmd.Parameters.Add(new SqlParameter("@UnitPrice", UnitPrice));
                con.Open();
                cmd.ExecuteNonQuery();
                con.Close();

                GridView1.EditIndex = -1;
                BindData();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        protected void AddNewRow()
        {
            //dt = new DataTable();
            //DataRow dr = null;
            //dt.Columns.Add(new DataColumn("PRODUCTID", typeof(string)));
            //dt.Columns.Add(new DataColumn("PRODUCTNAME", typeof(string)));
            //dt.Columns.Add(new DataColumn("UNITPRICE", typeof(string)));

            //dr = dt.NewRow();
            //dr["PRODUCTID"] = 14;
            //dr["PRODUCTNAME"] = string.Empty;
            //dr["UNITPRICE"] = string.Empty;

            //dt.Rows.Add(dr);

            //ViewState["CurrentTable"] = dt;


            //GridView1.DataSource = dt;
            //GridView1.DataBind();


            int rowIndex = 0;

            if (ViewState["CurrentTable"] != null)
            {
                DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
                DataRow drCurrentRow = null;
                if (dtCurrentTable.Rows.Count > 0)
                {
                    for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
                    {

                        int ProductID = Convert.ToInt32(GridView1.DataKeys[rowIndex].Value);
                        TextBox TextBoxName = (TextBox)GridView1.Rows[rowIndex].Cells[2].FindControl("txtProduct1");
                        TextBox TextBoxPrice = (TextBox)GridView1.Rows[rowIndex].Cells[3].FindControl("txtPrice1");

                        drCurrentRow = dtCurrentTable.NewRow();
                        drCurrentRow["PRODUCTID"] = ProductID + 1;
                        drCurrentRow["PRODUCTNAME"] = TextBoxName.Text;
                        drCurrentRow["UNITPRICE"] = TextBoxPrice.Text;
                        //dtCurrentTable.Rows[13 - 1]["PRODUCTID"] = ProductID + 1;
                        rowIndex++;
                    }

                    dtCurrentTable.Rows.Add(drCurrentRow);
                    ViewState["CurrentTable"] = dtCurrentTable;

                    GridView1.DataSource = dtCurrentTable;
                    GridView1.DataBind();
                }
            }
        }
        protected void button1_click(object sender, EventArgs e)
        {

            AddNewRow();
        }
    }
}

0 个答案:

没有答案