发生了System.NullReferenceException。你调用的对象是空的

时间:2013-05-15 13:03:30

标签: asp.net

    protected void DataList1_ItemCommand(object source, DataListCommandEventArgs e1)
    {
        if (e1.CommandName == "BuyClick")
        {
            Label iid_lbl = (Label)e1.Item.FindControl("iid_lbl");
            Label igid_lbl = (Label)e1.Item.FindControl("igid_lbl");
            Label iname_lbl = (Label)e1.Item.FindControl("iname_lbl");
            Label idesp_lbl = (Label)e1.Item.FindControl("idesp_lbl");
            Label iqty_lbl = (Label)e1.Item.FindControl("iqty_lbl");
            Label iprice_lbl = (Label)e1.Item.FindControl("iprice_lbl");
            Button Button1 = (Button)e1.Item.FindControl("Button1");
            str1 = "insert into orders values(' ',' ','" + igid_lbl.Text + "',' ',' ','" + iname_lbl.Text + "',' ')";
            str2 = "insert into order_item values(' ','" + iid_lbl.Text + "','" + idesp_lbl.Text + "',' ','" + iprice_lbl.Text + "','" + iqty_lbl.Text + "','" + iname_lbl.Text + "')";
            cmd1 = new MySqlCommand(str1, con1);
            cmd2 = new MySqlCommand(str2, con1);
            cmd1.ExecuteNonQuery();
            cmd2.ExecuteNonQuery();
            con1.Close();
            Response.Redirect("buy.aspx");
        }

    }

错误符合 str1 = "insert into orders values(' ',' ','" + igid_lbl.Text + "',' ',' ','" + iname_lbl.Text + "',' ')";

2 个答案:

答案 0 :(得分:0)

您似乎正在尝试访问网格/数据列表中的文本框。

如果是这种情况,则无法按照您尝试的方式进行访问。

您需要从网格中提取文本框/标签。

这样的事情:

if(e.Row.RowType == DataControlRowType.DataRow && e1.CommandName == "BuyClick") {
    Label igid = (Label)e.Row.FindControl("igid_lbl");
    Label iName = (Label)e.Row.FindControl("iname_lbl");

   // Do this for ALL your labels/textfields

    // now your inserts should reference these labels. Such as
    String str1 = "insert into orders values(' ',' ','" + igid.Text + "',' ',' ','" + iName.Text + "',' ')";

// ETC ETC ETC 

}

答案 1 :(得分:0)

请确保您已正确命名标签,如果标签不存在,则可能导致将null连接到可能导致错误的字符串。