0

I am doing project on asp.net. Right now I have got problem with insert data from gridview to sql server. In my gridview I have add a template as a textbox in order to input value. My problem is about insert value from textbox of gridview to sql server. My code as below:

<%@ Page Title="" Language="C#" MasterPageFile="~/coca.Master" AutoEventWireup="true"     CodeBehind="Orders.aspx.cs" Inherits="AssignmentWeb.Orders" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
    <div class="center">
     <script type="text/javascript"     src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript">
        $(function () {
            $("[id*=txtQty]").val("0");
        });
        $("[id*=txtQty]").live("change", function () {
            if (isNaN(parseInt($(this).val()))) {
                $(this).val('0');
            } else {
                $(this).val(parseInt($(this).val()).toString());
            }
        });
        $("[id*=txtQty]").live("keyup", function () {
            if (!jQuery.trim($(this).val()) == '') {
                if (!isNaN(parseFloat($(this).val()))) {
                    var row = $(this).closest("tr");
                    $("[id*=lblTotal]", row).html(parseFloat($(".price", row).html()) *     parseFloat($(this).val()));
                }
            } else {
                $(this).val('');
            }
            var grandTotal = 0;
            $("[id*=lblTotal]").each(function () {
                grandTotal = grandTotal + parseFloat($(this).html());
            });
            $("[id*=lblGrandTotal]").html(grandTotal.toString());
        });
    </script>
    <br />
    <asp:GridView ID="GridView1" runat="server" AllowPaging="True"     AutoGenerateColumns="False" DataKeyNames="ProductID" DataSourceID="SqlDataSource1"     EnableModelValidation="True">
        <Columns>
            <asp:BoundField DataField="ProductID" HeaderText="ProductID"     ReadOnly="True" SortExpression="ProductID" />
            <asp:BoundField DataField="ProductName" HeaderText="ProductName"     SortExpression="ProductName" />
            <asp:BoundField DataField="AverageProduct" HeaderText="AverageProduct"     SortExpression="AverageProduct" ItemStyle-CssClass="price"/>
            <asp:BoundField DataField="Description" HeaderText="Description"     SortExpression="Description" />
            <asp:TemplateField HeaderText="QtyOrder">
                <ItemTemplate>
                    <asp:Textbox ID="txtQty" runat="server"></asp:Textbox>
                 </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Total">
                <ItemTemplate>
                    <asp:Label ID="lblTotal" runat="server"></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>
     Grand Total:
    <asp:Label ID="lblGrandTotal" runat="server" Text="0"></asp:Label>
    <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$     ConnectionStrings:InventoryRouting %>" SelectCommand="SELECT [ProductName],     [AverageProduct], [Description], [ProductID] FROM [Product]"></asp:SqlDataSource>
&nbsp;<br />
    <asp:Button ID="btnOrder" runat="server" Text="Order!" Width="100px"     OnClick="btnOrder_Click"/>
    <br />
    <br />
    </div>
</asp:Content>

<script runat="server">
    public void btnOrder_Click(object sender, EventArgs e)
    {
        int c = 0;
        for (int i = 0; i < GridView1.Rows.Count; i++)
        {
            GridViewRow row = GridView1.Rows[i];
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = new SqlConnection("Data Source=LIDA-PC; Initial     Catalog=InventoryRouting; Integrated Security=True");
            //cmd.CommandText = "insert into orders values('" +     Session["Username"].ToString() + "',@ProductID, @ProductName, @QtyOrder, @Total)";
            cmd.CommandText = "insert into orders values('" +     Session["Username"].ToString() + "',@ProductID , @ProductName, @QtyOrder, @Total)";
            cmd.Connection .Open();
            //cmd.Parameters.AddWithValue("'" + Session["Username"].ToString() + "'",        GridView1.Rows[i].Cells[1].Text);
            cmd.Parameters.AddWithValue("@ProductID", GridView1.Rows[i].Cells[0].Text);
            cmd.Parameters.AddWithValue("@ProductName",     GridView1.Rows[i].Cells[1].Text);
            cmd.Parameters.AddWithValue("@QtyOrder", GridView1.Rows[i].Cells[4].Text);
            cmd.Parameters.AddWithValue("@Total", GridView1.Rows[i].Cells[5].Text);
            //InsertCommand = new SqlCommand("INSERT INTO [orders] ([client],     [product], [amount], [price]) VALUES ('" + Session["Username"].ToString() + "',     @ProductName, @AverageProduct, @QtyOrder, @Total)");
            cmd.ExecuteNonQuery();
            cmd.Connection.Close();
            c = c + 1;
        }
    }
</script>
1
  • Grid view shows you the stored data from sql. So you can't insert from grid view, I mean of course you can insert but this is not a proper way. So you should just update the fields. Commented May 24, 2013 at 6:19

1 Answer 1

1

You need to convert grid view row cell control to the appropriate control explicitly.

access like this ((Textbox)(GridView1.Rows[i].Cells[4].Controls[0]).Text for your @QtyOrder

and ((Label)(GridView1.Rows[i].Cells[5].Controls[0]).Text for @Total.

OR

(GridView1.Rows[i].FindControl("txtQty") as TextBox).Text

Thanks.

Sign up to request clarification or add additional context in comments.

2 Comments

Excuse me sir...right now I can insert into "txtQtyOrder", but Label "txtQty" I cannot insert it. I used: (GridView1.Rows[i].FindControl("txtQty") as TextBox).Text
You have the label as lblTotal in GridView. You can access it's value like this: (GridView1.Rows[i].FindControl("lblTotal") as Label).Text

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.