0
votes

I wrote code to add dynamic text boxes to the aspx page based on user input in specific text box but when i aim to save their value(dynamic text boxes) i face with below exception (because of object of text boxes in code behind stay null):

Object reference not set to an instance of an object. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

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

Source Error:

Line 99: { Line 100: con.Open(); Line 101: cmd.Parameters.AddWithValue("@name", txtName.Text); Line 102:
cmd.Parameters.AddWithValue("@mail", Convert.ToInt32(txtCost.Text)); Line 103: cmd.ExecuteNonQuery(); here is my markup code:

asp:Content ID="Content2" ContentPlaceHolderID="TitleContentPlaceHolder" runat="server">
    <img class="pull-right" src="/resources/cicons/event-title.png"  style="padding:10px;">
    <span class="pull-right"  style="color:gray;font-weight:bold;font-size:15px;padding:10px">تعریف کلاس</span>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="MainContentPlaceHolder" runat="server">
    <div style="margin-left: 13px; margin-top: 0px;direction: rtl;margin-bottom:50px" class="widget stacked widget-table action-table">
    <div class="span12 column">
        <asp:HiddenField runat="server" ID="AccordionHiddenField"  Value=".search"/>
        <div class="well span10" style="margin-top:5px;direction:rtl">
            <div class="row-fluid user-infos search" style="display: none;">
                <div class="span10 offset1">
                    <div class="panel-primary">
                        <div class="panel-body">
                            <div class="row-fluid">
                                <div class="span12">
                                        <div class="span6">
                                            <div class="form-group" style="width:400px">

                                                <asp:TextBox ID="txtProviderId" runat="server" Visible="False" Width="150px"></asp:TextBox>
                                            </div>
                                        </div>
                                    <div class="span12">
                                            <div class="form-group" style="width:400px">
                                                    <label class="span3" for="lblCount" style="float:right">تعداد کلاس</label>
                                                <asp:TextBox ID="txtCount" runat="server"></asp:TextBox>
                                            </div>
                                        </div>
                                            <div class="span6" style="margin-right: 310px;margin-left: -35px;">
                                                <button runat="server" onserverclick ="cmdOk_ServerClick"
                                                id="cmdOk" causesvalidation="false"
                                                style="float: right; margin-left: 10px;" 
                                                class="btn btn-success">
                                                افزودن کلاس
                                            </button>
                                        </div>
                                </div>
                            </div>
                        </div>

                    </div>
                </div>
            </div>
      </div>
        </div>
    </div>
    <div style="margin-left: 13px; margin-top: 0px;direction: rtl;margin-bottom:50px" class="widget stacked widget-table action-table">
    <div class="span12 column">
      <div class="well span10" style="margin-top:5px;direction:rtl">
        <div class="row-fluid user-infos search" style="display: none;">
          <div class="span10 offset1">
            <div class="panel-primary">
              <div class="panel-body">
                <div class="row-fluid">
                 <div class="span12">
                    <div class="span6">
                        <div class="form-group" style="width:400px">
                          <asp:PlaceHolder ID="mainplaceholder" runat="server">
                             <div class="span6" style="margin-right: 310px;margin-left: -35px;">
                                 <button runat="server" onserverclick ="cmdSubmit_ServerClick"
                                     id="cmdSubmit" causesvalidation="false"
                                     style="float: right; margin-left: 10px;" 
                                     class="btn btn-success">
                                       ثبت
                                 </button>
                            </div>
                          </asp:PlaceHolder>
                        </div>
                        </div>
                     </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        </div>
</asp:Content>

and here is code behind:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Hasin.Common.Utilities;
using HasinReservation.Classes;
using HasinReservation.Entities;
using HasinReservation.Entities.Db;
using HasinReservation.Utility.BasePage;
using System.Data.Entity.Infrastructure;
using System.Data.SqlClient;
using System.Web.Script.Serialization;
using System.Configuration;
using System.Data;

namespace HasinReservation.UI.ServiceProvider
{
    public partial class _Levels : System.Web.UI.Page
    {

        protected void Page_Load(object sender, EventArgs e)
        {
            txtProviderId.Text = ((CurrentUser)Session["currentuser"]).ProviderId.ToString();
            if (!Page.IsPostBack)
            {
                // BindCombos();
                DataBind();
            }
        }
        private void BindCombos()
        {

        }
        protected void cmdOk_ServerClick(object sender, EventArgs e)
        {
            for (int j = 1; j <= Convert.ToInt32(txtCount.Text); j++)

            {
                Label lbl1 = new Label();
                lbl1.Text = "کلاس شماره" + j;
                lbl1.ID = "lblName";
                mainplaceholder.Controls.Add(lbl1);
                mainplaceholder.Controls.Add(new LiteralControl("&nbsp;"));
                mainplaceholder.Controls.Add(new LiteralControl("&nbsp;"));
                mainplaceholder.Controls.Add(new LiteralControl("&nbsp;"));
                mainplaceholder.Controls.Add(new LiteralControl("&nbsp;"));
                mainplaceholder.Controls.Add(new LiteralControl("&nbsp;"));
                mainplaceholder.Controls.Add(new LiteralControl("&nbsp;"));
                mainplaceholder.Controls.Add(new LiteralControl("&nbsp;"));
                mainplaceholder.Controls.Add(new LiteralControl("&nbsp;"));
                mainplaceholder.Controls.Add(new LiteralControl("&nbsp;"));
                mainplaceholder.Controls.Add(new LiteralControl("&nbsp;"));
                mainplaceholder.Controls.Add(new LiteralControl("&nbsp;"));
                TextBox txt = new TextBox();
                txt.ID = "txtName" + j.ToString();
                mainplaceholder.Controls.Add(txt);
                mainplaceholder.Controls.Add(new LiteralControl("<br />"));
                Label lbl2 = new Label();
                lbl2.Text = "قیمت کلاس شماره" + j;
                lbl2.ID = "lblCost";
                mainplaceholder.Controls.Add(lbl2);
                mainplaceholder.Controls.Add(new LiteralControl("&nbsp;"));
                TextBox tb = new TextBox();
                tb.ID = "txtCost" + j.ToString();
                mainplaceholder.Controls.Add(tb);
                mainplaceholder.Controls.Add(new LiteralControl("<br />"));
                cmdSubmit.Visible = true;

            }


        }

        protected void cmdSubmit_ServerClick(object sender, EventArgs e)
        {
            int j = Convert.ToInt32(txtCount.Text);
            for (int i = 1; i<j;i++){
            String str = string.Empty;
            TextBox txtName = (TextBox)mainplaceholder.FindControl("txtName" + i.ToString());

            TextBox txtCost = (TextBox)mainplaceholder.FindControl("txtCost" + i.ToString());
            using (SqlConnection con = new SqlConnection(@"Data Source=192.168.10.4\Sql2008;Initial Catalog=GardeshgariKish;User ID=cms;Password=cms#123456;MultipleActiveResultSets=True;Application Name=EntityFramework"))
            {
                using (SqlCommand cmd = new SqlCommand("INSERT INTO Seat(Name,cost) VALUES(@name,@mail)", con))
                {
                    con.Open();
                    cmd.Parameters.AddWithValue("@name", txtName.Text);
                    cmd.Parameters.AddWithValue("@mail", Convert.ToInt32(txtCost.Text));
                    cmd.ExecuteNonQuery();
                    txtCost.Text = string.Empty;
                    txtName.Text = string.Empty;
                    ClientScript.RegisterClientScriptBlock(this.GetType(), "btn", "<script type = 'text/javascript'>alert('UserDetails saved Successfully');</script>");

                }

            }
         }
        }
    }
}
2

2 Answers

0
votes

Id had a similar issue to this in the past. In order to fix it, I needed to run statements to check for null or empty entries before the sql was run.

  if (string.IsNullOrEmpty(string))
        {
            sqlQuery.Parameters.Add("@string", SqlDbType.VarChar, 50).Value = DBNull.Value;
        }
        else
        {
            sqlQuery.Parameters.Add("@string", SqlDbType.VarChar, 50).Value = string;
        }

This example should help. You just need to check each variable for null entries and assign the DBNull value to it instead if it is empty

0
votes

The problem with dynamic control is you will need to reload the control (with same id) on every post back of the page.

Otherwise, they'll not be in the control tree, and you won't be able to find them.

Here is a sample. It loads TextBox control dynamically, and displays the value back when Submit button is clicked.

ASPX

<asp:PlaceHolder runat="server" ID="PlaceHolder1" />
<asp:Button runat="server" ID="OkButton" OnClick="OkButton_Click" Text="Ok" />
<asp:Button runat="server" ID="SubmitButton" OnClick="SubmitButton_Click" Text="Submit" />
<asp:Label runat="server" ID="MessageLabel" />

Code Behind

protected void Page_Init(object sender, EventArgs e)
{
    if (IsPostBack)
    {
        LoadControls();
    }
}

protected void OkButton_Click(object sender, EventArgs e)
{
    LoadControls();
}

protected void SubmitButton_Click(object sender, EventArgs e)
{
    var myTextBox = FindControlRecursive(PlaceHolder1, "MyTextBox") as TextBox;
    MessageLabel.Text = myTextBox.Text;
}

private void LoadControls()
{
    // Ensure that the control hasn't been added yet. 
    if (FindControlRecursive(PlaceHolder1, "MyTextBox") == null)
    {
        var myTextBox = new TextBox {ID = "MyTextBox"};
        PlaceHolder1.Controls.Add(myTextBox);
    }
}

public static Control FindControlRecursive(Control root, string id)
{
    if (root.ID == id)
        return root;

    return root.Controls.Cast<Control>()
        .Select(c => FindControlRecursive(c, id))
        .FirstOrDefault(c => c != null);
}