Avatar of stu29
stu29
Flag for United States of America asked on

ASP.NET & C# Question: System.NullReferenceException: Object reference not set to an instance of an object.

I'm getting
System.NullReferenceException: Object reference not set to an instance of an object.
when I'm just trying to read a value from a DetailsView on ItemInserting.
[in aspx]
<asp:DetailsView ID="DetailsView1" runat="server" AutoGenerateRows="False" 
            DataKeyNames="BinCategoryID" DataSourceID="SqlDataSource2" 
            Height="50px" Width="125px" OnItemInserting="DetailsView1_ItemInserting" 
            DefaultMode="Insert" onpageindexchanging="DetailsView1_PageIndexChanging">
            <Fields>
...
<InsertItemTemplate>
                        <asp:TextBox ID="tbInsertBinCategory" runat="server" Text='<%# Bind("BinCategory") %>'></asp:TextBox>
                    </InsertItemTemplate>
 
[in code behind]
protected void DetailsView1_ItemInserting(object sender, DetailsViewInsertEventArgs e)
        {
            Label3.Text = e.Values["tbInsertBinCategory"].ToString();  (<- erroring here)

Open in new window

ASP.NET

Avatar of undefined
Last Comment
Padre_Corleone

8/22/2022 - Mon
Padre_Corleone

try ItemInserted instead.  also the value may not be found if your details view is getting wiped out before or information is not loaded on  your page load.
stu29

ASKER
My goal is to do a customized input validation.  I thought OnItemInserting event is a good place to read in the user input and do my validation.  (I want to then query the DB to see if the value already exists.)

Anyway, I moved the codes to the OnItemIInserted and I get this error now:

Compiler Error Message: CS0123: No overload for 'DetailsView1_ItemInserted' matches delegate 'System.Web.UI.WebControls.DetailsViewInsertedEventHandler'

Source Error:
Line 76:     </div>
Line 77:     <div id="divInsert">
Line 78:         <asp:DetailsView ID="DetailsView1" runat="server" AutoGenerateRows="False"
Line 79:             DataKeyNames="BinCategoryID" DataSourceID="SqlDataSource2"
Line 80:             Height="50px" Width="125px" OnItemInserting="DetailsView1_ItemInserting"

Thanks,
stu29

ASKER
Aah, I had a wrong param for the function:
        protected void DetailsView1_ItemInserted(object sender, DetailsViewInsertedEventArgs e)
        {
            Label3.Text = e.Values["tbInsertBinCategory"].ToString();

But I still have the same error even under ItemInserted:

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error:
Line 84:         protected void DetailsView1_ItemInserted(object sender, DetailsViewInsertedEventArgs e)
Line 85:         {
Line 86:             Label3.Text = e.Values["tbInsertBinCategory"].ToString();
Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes
stu29

ASKER
So I'm simply trying to validate the user input if it doesn't exists in the DB already before I let it to be inserted.  If anyone has source codes, that's all I need. Thanks.
Padre_Corleone

ok try

  TextBox txtBox = DetailsView1.FindControl("tbInsertBinCategory");
   if not isnothing(txtBox ) then
     txtBox.text = ""
  end
Padre_Corleone

I just tested and now it works for me please see code below:
    <asp:DetailsView runat="server" ID="DetailsViewTest"  OnItemInserting="DetailsViewTest_ItemInserting" AutoGenerateRows="false" DataKeyNames="ID" Height="50px" Width="125px"
    DefaultMode="Insert" AutoGenerateInsertButton="true">
    <Fields>
        <asp:TemplateField HeaderText="UserName">
            <InsertItemTemplate>
                <asp:TextBox ID="tbInsertBinCategory" runat="server" Text='<%# Bind("username") %>'></asp:TextBox>
            </InsertItemTemplate>
        </asp:TemplateField>
    </Fields>
    </asp:DetailsView>
 
 
    Public Sub DetailsViewTest_ItemInserting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DetailsViewInsertEventArgs) Handles DetailsViewTest.ItemInserting
        Dim oTextBox As TextBox = CType(Me.DetailsViewTest.FindControl("tbInsertBinCategory"), TextBox)
        If Not IsNothing(oTextBox) Then
            oTextBox.Text = "Found"
        End If
    End Sub
 
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
           LoadDetailsView()
        End If
    End Sub

Open in new window

⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
stu29

ASKER
Well, for some reason I can't get it working so I got rid of the DetailsView and created input boxes to take user inputs and insert to the DB.  Now that's working and I also added a CustomValidator which is working but when the validator is activated (args.IsValid = false), the form still finishes and inserts a record.

[in the .cs]
        public void InsertBinCategory(string bincategory, string active)
        {
        .....
        }

        protected void Button_Add_Click(object sender, EventArgs e)
        {
            InsertBinCategory(TextBox_BinCategory.Text, "");
        }

        protected void CustomValidator_BinCategory(Object source, ServerValidateEventArgs args)
        {
            string strQuery = "SELECT BinCategoryID from BinCategory " +
                                "WHERE BinCategory = '" + args.Value + "'";
            if (ValueExists(strQuery))
                    args.IsValid = false;
            else
                    args.IsValid = true;
        }

        private bool ValueExists(string strQeury)
        {
        .......
        }

[in the .aspx]
<asp:TextBox ID="TextBox_BinCategory" runat="server"></asp:TextBox>
<asp:CustomValidator id="CustomValidator1" Runat="server" ErrorMessage="already exists"
ControlToValidate="TextBox_BinCategory" OnServerValidate="CustomValidator_BinCategory" />
<asp:Button ID="Button_Add" runat="server" onclick="Button_Add_Click" Text="Add" />

I enter a duplicate value and hit submit.  It display the error msg. "already exists" but it still goes thru InsertBinCategory and ends up inserting a record.
ASKER CERTIFIED SOLUTION
Padre_Corleone

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.