我从gridview保存数据时出错

时间:2016-01-28 03:33:09

标签: c# asp.net gridview

您好我的客户有一个网格视图,可以有很多数据(产品)

问题是每当我点击保存时,就会出现错误

Object reference not set to an instance of an object. 
Line 109:cmd.Parameters.Add("@RefNo", SqlDbType.VarChar).Value = RefNo.Text;

这是我的gridview的图片:

这是我的代码(ASP)

    <asp:GridView ID="GridView1" runat="server" AllowPaging="True" 
    AutoGenerateColumns="False" DataKeyNames="RefNo" DataSourceID="SqlDataSource1">
    <Columns>
        <asp:BoundField DataField="RefNo" HeaderText="RefNo" InsertVisible="False" 
            ReadOnly="True" SortExpression="RefNo" />
        <asp:BoundField DataField="ProductID" HeaderText="ProductID" 
            SortExpression="ProductID" />
        <asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
        <asp:BoundField DataField="Quantity" HeaderText="Quantity" 
            SortExpression="Quantity" />
        <asp:BoundField DataField="Price" HeaderText="Price" SortExpression="Price" />
        <asp:BoundField DataField="Amount" HeaderText="Amount" 
            SortExpression="Amount" />
    </Columns>

</asp:GridView>

<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
    ConnectionString="<%$ ConnectionStrings:MyOwnMeatshopConnectionString %>" 
    SelectCommand="SELECT Orders.RefNo, Orders.ProductID, Products.Name, Orders.Quantity, Orders.Price, Orders.Amount FROM Orders INNER JOIN Products ON Orders.ProductID = Products.ProductID">
</asp:SqlDataSource>

<asp:Button ID="btnSave" runat="server" class="btn btn" Text="Save" 
    style="color:White" BackColor="Black" onclick="btnSave_Click"/>

这是Code Behind

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;

using System.Data;
using System.Data.SqlClient;

namespace MyOwnMeatshop.User.Orders.SO
{
    public partial class Default : System.Web.UI.Page
    {
        SqlConnection con = new SqlConnection(Helper.GetCon());

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                GetUserSO();

            }
        }

        void GetUserSO()
        {
            con.Open();
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = con;
            cmd.CommandText = "SELECT SOID, FirstName, LastName, Status, DateOrdered FROM SO";
            cmd.Parameters.AddWithValue("@UserID", Session["userid"].ToString());
            SqlDataReader dr = cmd.ExecuteReader();
            while (dr.Read())
            {
                SOID.Text = dr["SOID"].ToString();
                LbFN.Text = dr["FirstName"].ToString();
                LbLN.Text = dr["LastName"].ToString();
                LbStatus.Text = dr["Status"].ToString();
                LbDateOrdered.Text = dr["DateOrdered"].ToString();

            }
            con.Close();
        }

        decimal GetPrice(int ID) // get price of the selected product
        {
            decimal price = 0;
            con.Open();
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = con;
            cmd.CommandText = "SELECT Price FROM Products " +
                "WHERE ProductID=@ProductID";
            cmd.Parameters.AddWithValue("@ProductID", ID);
            price = (decimal)cmd.ExecuteScalar(); // typecasting

            con.Close();
            return price;
        }

        void GetCart()
        {
            con.Open();
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = con;
            cmd.CommandText = "SELECT Products.ProductID, Products.Name, Orders.RefNo, " +
                "Products.Price, Orders.Quantity, " +
                "Orders.Amount FROM Orders " +
                "INNER JOIN Products ON Orders.ProductID = Products.ProductID " +
                "WHERE Orders.UserID=@UserID AND Orders.Status='In Cart'";
            cmd.Parameters.AddWithValue("@UserID", Session["userid"].ToString());
            //cmd.Parameters.Add("@UserID", SqlDbType.Int).Value = Session["userid"].ToString();
            SqlDataReader dr = cmd.ExecuteReader();

            con.Close();
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            foreach (GridViewRow row in GridView1.Rows)
            {
                if (row.RowType == DataControlRowType.DataRow)
                {
                    Label RefNo = row.FindControl("RefNo") as Label;
                    Label ProductID = row.FindControl("ProductID") as Label;
                    Label Name = row.FindControl("Name") as Label;
                    Label Quantity = row.FindControl("Quantity") as Label;
                    Label Price = row.FindControl("Price") as Label;
                    Label Amount = row.FindControl("Amount") as Label;

                    con.Open();
                    SqlCommand cmd = new SqlCommand();
                    cmd.Connection = con;
                    cmd.CommandText = "INSERT INTO SODetails (UserID, SOID, RefNo, ProductID, Name, Price, Quantity) VALUES (@UserID, @SOID, @RefNo, @ProductID, @Name, @Price, @Quantity)";

                    cmd.Parameters.AddWithValue("@UserID", Session["userid"].ToString());
                    //cmd.Parameters.AddWithValue("@SOID", SOID.Text);
                    //cmd.Parameters.AddWithValue("@RefNo", RefNo);
                    //cmd.Parameters.AddWithValue("@ProductID", ProductID);
                    //cmd.Parameters.AddWithValue("@Name", Name);
                    //cmd.Parameters.AddWithValue("@Price", Price);
                    //cmd.Parameters.AddWithValue("@Quantity", Quantity);

                    cmd.Parameters.Add("@SOID", SqlDbType.VarChar).Value = SOID.Text;
                    cmd.Parameters.Add("@RefNo", SqlDbType.VarChar).Value = RefNo.Text;
                    cmd.Parameters.Add("@ProductID", SqlDbType.VarChar).Value = ProductID.Text;
                    cmd.Parameters.Add("@Name", SqlDbType.VarChar).Value = Name.Text;
                    cmd.Parameters.Add("@Price", SqlDbType.VarChar).Value = Price.Text;
                    cmd.Parameters.Add("@Quantity", SqlDbType.VarChar).Value = Quantity.Text;
                    cmd.Parameters.Add("@Amount", SqlDbType.VarChar).Value = Amount.Text;

                    cmd.ExecuteNonQuery();

                    cmd.CommandText = "SELECT SOID, RefNo, ProductID, Name, Price, Quantity, Amount FROM MYTABLE";

                    GridView1.EditIndex = -1;
                    GridView1.DataBind();

                    con.Close();
                }
            }
        }
    }
}

2 个答案:

答案 0 :(得分:0)

如果使用模板字段而不是“绑定字段”,这将很容易处理。您可以从“字段”对话框中将“绑定字段”转换为“模板字段”。

答案 1 :(得分:0)

在您的代码中,您使用的是绑定字段。您可以通过以下方式获取标签值

使用数据密钥获取它,您可以在任何需要的地方编写此代码。

var RefNo= GridView1.DataKeys[rowIndex].Values[0].ToString();

或者通过细胞获取它:

string RefNo= GridView1.Rows[RowIndex].Cells[BoundFieldIndex].Text;