对象引用没有设置为对象的实例

时间:2022-12-04 15:15:06

I am Having problem with object reference.But a similar page is working properly.there is no problem with the database.

我对对象引用有问题。但是一个类似的页面正在正常工作。数据库没有问题。

enter code here

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Web.Configuration;

public partial class PO_Receipt_entry : System.Web.UI.Page
{
Logic PO;
DataSet ds,ds1;
Label l=new Label ();

protected void Page_Load(object sender, EventArgs e)
{
    if (Session["username"] == null)
    {
        Response.Redirect("Relogin.aspx");
    }
    PO = new Logic();
    if (!IsPostBack)
    {
        MultiView1.ActiveViewIndex = 0;
    }
}
private int TextBoxCount1
{
    get
    {
        var count = ViewState["txtBoxCount1"];
        return (count == null) ? 0 : (int)count;
    }
    set { ViewState["txtBoxCount1"] = value; }
}
private void AddTextBox(int index)
{
    var txtq = new TextBox { ID = string.Concat("txtbxq", index) };
    txtq.CssClass = "bordered-link";
    PlaceHolder2.Controls.Add(txtq);
    PlaceHolder2.Controls.Add(new LiteralControl("<br/><br/>"));
    Response.Write(txtq.ID);

}
private void AddLabel(int ind)
{
    var lblm = new Label { ID = string.Concat("lblm", ind) };
    PlaceHolder1.Controls.Add(lblm);
    PlaceHolder1.Controls.Add(new LiteralControl("<br/><br/>"));
    lblm.Text = ds1.Tables[0].Rows[ind]["Md"].ToString();

}
private void AddLabelQ(int ind)
{
    var lblq = new Label { ID = string.Concat("lblq", ind) };
    PlaceHolder5.Controls.Add(lblq);
    PlaceHolder5.Controls.Add(new LiteralControl("<br/><br/>&nbsp;"));
    TextBox ttt = (TextBox)PlaceHolder2.FindControl(("txtbx" + ind).ToString());
    lblq.Text = ttt.Text;

}
protected void Button3_Click(object sender, EventArgs e)
{
    MultiView1.ActiveViewIndex = 1;
    ds=PO.FillDataset("select VendorName+' - '+ContactPerson as Vd from PurchaseOrder        INNER JOIN Vendor ON PurchaseOrder.VendorID=Vendor.VendorID where      POnumeric='"+TextBox1.Text+"'");
    Label1.Text=ds.Tables[0].Rows[0]["Vd"].ToString();
    TextBoxCount1 =(int)PO.ExecuteScalar("Select COUNT(1) from MaterialsPurchased where     POnumeric='" + TextBox1.Text + "'");
    ds1 = PO.FillDataset("select MaterialsPurchased.MaterialID,MType+' - '+Shape+' - '+Dimensions as Md from MaterialsPurchased INNER JOIN Material ON MaterialsPurchased.MaterialID=Material.MaterialID where POnumeric='"+TextBox1.Text+"'");

    l.Text = TextBoxCount1.ToString();
    if (TextBoxCount1 > 0)
    {
        PlaceHolder2.Visible = true;
        PlaceHolder1.Visible = true;
        PlaceHolder3.Visible = true;
        PlaceHolder4.Visible = true;
        for (int i =0; i < TextBoxCount1; i++)
        {

            AddLabel(i);
            AddTextBox(i);
        }
    }
}


protected void Button1_Click(object sender, EventArgs e)
{
    MultiView1.ActiveViewIndex = 1;
    PlaceHolder5.Visible = true;
   for (int i = 0; i < TextBoxCount1; i++)
    {
        AddLabelQ(i);
        PO.ExecuteNonQuery("update MaterialsPurchased set Quantity='" + t.Text + "'     where POnumeric='"+TextBox1.Text+"' and MaterialID='"+ds1.Tables[0].Rows[i]["MaterialID"].ToString()+"'");

}

}

}
protected void Button2_Click(object sender, EventArgs e)
{

}
}

I am having error with the line

我对这条线有错误

TextBox ttt = (TextBox)PlaceHolder2.FindControl(("txtbx" + ind).ToString());

while debugging the value of ttt is coming out to be null

虽然调试ttt的值是空的。

But a similar page is working properly

但类似的页面正在正常工作

enter code here


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Text;
using System.Collections;
using System.Windows;
public partial class Purchase_oreder_entry : System.Web.UI.Page
{

Logic PurchaseOrder;


int flag = -1;

protected void Page_Load(object sender, EventArgs e)
{
    if (Session["username"] == null)
    {
        Response.Redirect("Relogin.aspx");
    }

    Multiview1.ActiveViewIndex = 0;
    try
    {
        PlaceHolder3.Visible = true;
       PlaceHolder4.Visible = true;
        PurchaseOrder = new Logic();


        if(!IsPostBack)
        PurchaseOrder.FillDropDownList(DropDownList1, @"Select VendorID,VendorName + '     \ '+ ContactPerson +' \ '+ PhoneNumber as vend from Vendor");

        if (Page.IsPostBack && flag==-1)
        {
            for(var i = 0; i <TextBoxCount; i++)
            {
                AddDropDownList(i);
                AddTextBox(i);


            }
        }

    }
    catch (Exception)
    {
        MessageBox.Show("Error !");
    }
}
private int TextBoxCount
{
    get
    {
        var count = ViewState["txtBoxCount"];
        return (count == null) ? 0 : (int)count;
    }
    set { ViewState["txtBoxCount"] = value; }
}

private void AddDropDownList(int index)
{

  var ddl = new DropDownList { ID = string.Concat("drdl", index) };
    ddl.AppendDataBoundItems = true;
    PurchaseOrder.FillDropDownList(ddl, @"Select MaterialID,Mtype + ' \ ' + Shape + ' \ ' + Dimensions from Material");

    ddl.CssClass = "bordered-link";
    PlaceHolder3.Controls.Add(ddl);
    PlaceHolder3.Controls.Add(new LiteralControl("<br/><br/>"));

}
private void AddTextBox(int index)
{
    var txt = new TextBox { ID = string.Concat("txtbx", index) };


    txt.CssClass = "bordered-link";
    PlaceHolder4.Controls.Add(txt);
    PlaceHolder4.Controls.Add(new LiteralControl("<br/><br/>"));


}
private void AddLabelM(int ind)
{
    var lblm = new Label { ID = string.Concat("lblm", ind) };
    PlaceHolder1.Controls.Add(lblm);
    PlaceHolder1.Controls.Add(new LiteralControl("<br/><br/>&nbsp;"));
    DropDownList d = (DropDownList)PlaceHolder3.FindControl(("drdl" + ind).ToString());
    if (d.SelectedItem.Text != "---select---")
    {

        lblm.Text =(ind+1)+") "+ d.SelectedItem.Text;
        PurchaseOrder.ExecuteNonQuery("insert into MaterialsPurchased values('" + POID.Text + "','" + d.SelectedValue + "','',0,'')");
    }
}

private void AddLabelQ(int ind)
{
    var lblq = new Label { ID = string.Concat("lblq", ind) };
    PlaceHolder2.Controls.Add(lblq);
    PlaceHolder2.Controls.Add(new LiteralControl("<br/><br/>&nbsp;"));
    TextBox t = (TextBox)PlaceHolder4.FindControl(("txtbx" + ind).ToString());
    lblq.Text = t.Text;

}

protected void Button1_Click(object sender, EventArgs e)
{


    Multiview1.ActiveViewIndex = 1;
    try
    {

        string po_id = UniqueId.Get();

        SqlDataReader dr = PurchaseOrder.ExecuteReader("Select * from Vendor where VendorID='" + DropDownList1.SelectedValue + "'");
        while (dr.Read())
        {
            VendorID.Text = dr[0].ToString();
            VendorName.Text = dr[1].ToString();
            ContactP.Text = dr[2].ToString();
            ContactNo.Text = dr[3].ToString();
            POID.Text = po_id;

        }

        dr.Close();
        PurchaseOrder.CloseConnection();
        for (int i = 0; i < TextBoxCount; i++)
        {

            AddLabelM(i);

            AddLabelQ(i);

        }
            PlaceHolder1.Visible = true;
        PlaceHolder2.Visible = true;
        Label1.Text = DateTime.Now.ToString();
        PurchaseOrder.ExecuteNonQuery("insert into PurchaseOrder values('"+POID.Text+"','"+VendorID.Text+"','"+DateTime.Parse(Label1.Text)+"')");

        MessageBox.Show("Purchase Order Created . Purchase Order ID:" + POID.Text);


    }

    catch (Exception)
    {
        MessageBox.Show("Error Occurred ! Please Try again.");
    }
}
protected void Button2_Click(object sender, EventArgs e)
{
    Response.Redirect("~/Home.aspx");
}
protected void LinkButton5_Click(object sender, EventArgs e)
{
    Response.Redirect("~/Material_new.aspx");
}
protected void LinkButton6_Click(object sender, EventArgs e)
{
    flag = 1;
    AddTextBox(TextBoxCount);
    AddDropDownList(TextBoxCount);
    TextBoxCount++;
}



protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
    Response.Redirect("~/Home.aspx",true);
}
protected void LinkButton7_Click(object sender, EventArgs e)
{
    Response.Redirect("~/Vendor_new.aspx");
}
}

3 个解决方案

#1


0  

The reason one code block works and the other doesn't is because - on the working one - you're adding them during the page_load.

一个代码块和另一个代码块不工作的原因是——在工作中——你在page_load中添加它们。

In the code that doesn't work you're adding them at the click of a button Button3_Click.

在不工作的代码中,单击按钮Button3_Click就可以添加它们。

What's actually happening is when you perform your button click AddLabelQ the textboxes you added via the click are not actually present.

实际发生的情况是当你执行按钮单击AddLabelQ时你通过点击添加的文本框实际上并不存在。

Dynamically created controls need to be re-created during the postback so they can be used by subsequent methods.

需要在回发期间重新创建动态创建的控件,以便后续方法可以使用它们。

The way a page works is first your page_load gets called (it's also first when you postback from a button click) and then your click handler will be fired. For example sake page_load is the first event handled in your code - others may use pre_init etc..

页面的工作方式是首先调用page_load(从单击按钮回发也是第一次),然后触发单击处理程序。例如,page_load是您的代码中处理的第一个事件——其他人可以使用pre_init等。

So in your code that doesn't work, you click a button, then page_load is called and then finally your LabelQ gets called - and in that chain you have not re-created your dynamically created controls.

在你的代码中,你点击一个按钮,然后page_load被调用,最后你的LabelQ被调用——在那个链中你没有重新创建你动态创建的控件。

so the fix - you need to keep track of buttons you created via your Button3_Click - perhaps by storing an array of Textbox's in session, then in your postback re-create them.

因此,解决方法是——您需要跟踪您通过Button3_Click创建的按钮——可能通过将Textbox的数组存储在会话中,然后在回发中重新创建它们。

so i pseudo-code (this has NOT been tested, it's just to give an idea)

我的伪代码(这还没有经过测试,只是为了给大家一个提示)

in your button3

在你button3

//create your textbox..

if (Session["myBoxes"] == null){
   // create a new list and add it to this session
   Session["myBoxes"] = new List<Textbox>;
}
// now you can add the textbox to the list in the session
List<Textbox>(Session["myBoxes")).Add(txtQ);

And now in your page_load..

现在在page_load。

if (!IsPostback){

  // see if there are any buttons..
  List<Textbox> txt = List<Textbox>(Session["myBoxes"));
  // loop through the boxes and re-create them

}else{
    // dump the Session here on the page initial load so it's not following the user around the site
   Session["myBoxes"] = null;
}

your boxes will now be available by the time your code gets to your button click.

当您的代码到达您的按钮单击时,您的方框将会可用。

Just remember to clear this session on the pages initial load as in the example above

请记住,在上面的示例中,在页面初始加载时清除这个会话。

#2


0  

There's a q missing

有一个问失踪

TextBox ttt = (TextBox)PlaceHolder2.FindControl(("txtbx" + ind).ToString());
                                                       ^ here

You're creating the control with an id of "txtbxq" + ind, I gues that is what you try to retrieve:

您正在创建一个id为“txtbxq”+ ind的控件,您试图检索的是:

var txtq = new TextBox { ID = string.Concat("txtbxq", index) };

#3


0  

you have added textbox control with id txtbxq into the content PlaceHolder2.Change it either ,
var txtq = new TextBox { ID = string.Concat("txtbx", index) }; or you can change while finding control

您已经在content PlaceHolder2中添加了id为txtbxq的文本框控件。或者更改它,var txtq = new TextBox {ID = string。Concat(“txtbx”,指数)};或者你可以在找到控制权的同时进行改变

TextBox ttt = (TextBox)PlaceHolder2.FindControl(("txtbxq" + ind).ToString());

and also you have to alert while concat . index that you have used should be same as per your finding control.

同时你也要注意。您使用的索引应该与您的查找控件相同。

#1


0  

The reason one code block works and the other doesn't is because - on the working one - you're adding them during the page_load.

一个代码块和另一个代码块不工作的原因是——在工作中——你在page_load中添加它们。

In the code that doesn't work you're adding them at the click of a button Button3_Click.

在不工作的代码中,单击按钮Button3_Click就可以添加它们。

What's actually happening is when you perform your button click AddLabelQ the textboxes you added via the click are not actually present.

实际发生的情况是当你执行按钮单击AddLabelQ时你通过点击添加的文本框实际上并不存在。

Dynamically created controls need to be re-created during the postback so they can be used by subsequent methods.

需要在回发期间重新创建动态创建的控件,以便后续方法可以使用它们。

The way a page works is first your page_load gets called (it's also first when you postback from a button click) and then your click handler will be fired. For example sake page_load is the first event handled in your code - others may use pre_init etc..

页面的工作方式是首先调用page_load(从单击按钮回发也是第一次),然后触发单击处理程序。例如,page_load是您的代码中处理的第一个事件——其他人可以使用pre_init等。

So in your code that doesn't work, you click a button, then page_load is called and then finally your LabelQ gets called - and in that chain you have not re-created your dynamically created controls.

在你的代码中,你点击一个按钮,然后page_load被调用,最后你的LabelQ被调用——在那个链中你没有重新创建你动态创建的控件。

so the fix - you need to keep track of buttons you created via your Button3_Click - perhaps by storing an array of Textbox's in session, then in your postback re-create them.

因此,解决方法是——您需要跟踪您通过Button3_Click创建的按钮——可能通过将Textbox的数组存储在会话中,然后在回发中重新创建它们。

so i pseudo-code (this has NOT been tested, it's just to give an idea)

我的伪代码(这还没有经过测试,只是为了给大家一个提示)

in your button3

在你button3

//create your textbox..

if (Session["myBoxes"] == null){
   // create a new list and add it to this session
   Session["myBoxes"] = new List<Textbox>;
}
// now you can add the textbox to the list in the session
List<Textbox>(Session["myBoxes")).Add(txtQ);

And now in your page_load..

现在在page_load。

if (!IsPostback){

  // see if there are any buttons..
  List<Textbox> txt = List<Textbox>(Session["myBoxes"));
  // loop through the boxes and re-create them

}else{
    // dump the Session here on the page initial load so it's not following the user around the site
   Session["myBoxes"] = null;
}

your boxes will now be available by the time your code gets to your button click.

当您的代码到达您的按钮单击时,您的方框将会可用。

Just remember to clear this session on the pages initial load as in the example above

请记住,在上面的示例中,在页面初始加载时清除这个会话。

#2


0  

There's a q missing

有一个问失踪

TextBox ttt = (TextBox)PlaceHolder2.FindControl(("txtbx" + ind).ToString());
                                                       ^ here

You're creating the control with an id of "txtbxq" + ind, I gues that is what you try to retrieve:

您正在创建一个id为“txtbxq”+ ind的控件,您试图检索的是:

var txtq = new TextBox { ID = string.Concat("txtbxq", index) };

#3


0  

you have added textbox control with id txtbxq into the content PlaceHolder2.Change it either ,
var txtq = new TextBox { ID = string.Concat("txtbx", index) }; or you can change while finding control

您已经在content PlaceHolder2中添加了id为txtbxq的文本框控件。或者更改它,var txtq = new TextBox {ID = string。Concat(“txtbx”,指数)};或者你可以在找到控制权的同时进行改变

TextBox ttt = (TextBox)PlaceHolder2.FindControl(("txtbxq" + ind).ToString());

and also you have to alert while concat . index that you have used should be same as per your finding control.

同时你也要注意。您使用的索引应该与您的查找控件相同。