将动态文本框的值添加到数据库

时间:2015-10-12 13:45:59

标签: c# asp.net sql-server

我编写了代码,根据特定文本框中的用户输入将动态文本框添加到aspx页面,但是当我的目标是保存它们的值(动态文本框)时,我面对下面的异常(因为代码中的文本框对象)留下留空):

对象引用未设置为对象的实例。 描述:执行当前Web请求期间发生未处理的异常。请查看堆栈跟踪,以获取有关错误及其在代码中的起源位置的更多信息。

异常详细信息:System.NullReferenceException:未将对象引用设置为对象的实例。

  

来源错误:

     

第99行:{第100行:con.Open();   第101行:cmd.Parameters.AddWithValue(“@ name”,   txtName.Text); 102行:
  cmd.Parameters.AddWithValue(“@ mail”,Convert.ToInt32(txtCost.Text));   第103行:cmd.ExecuteNonQuery();   这是我的标记代码:

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>

以下是代码:

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 个答案:

答案 0 :(得分:0)

我过去曾遇到类似的问题。为了解决这个问题,我需要在运行sql之前运行语句来检查null或空条目。

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

这个例子应该有所帮助。您只需检查每个变量是否为空条目,并为其分配DBNull值,如果它为空

答案 1 :(得分:0)

动态控制的问题是你需要在页面的每个帖子上重新加载控件(具有相同的id)。

否则,它们将不在控制树中,您将无法找到它们。

这是一个示例。它动态加载TextBox控件,并在单击Submit按钮时显示该值。

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" />

代码背后

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);
}