Search code examples
c#asp.netsql-serverwebformssqldatasource

ASP.NET Cannot insert the value NULL into column ‘name’


I have One Users table, columns: id, name, surname. I am trying to make simple insert functionality, but when I submit form I get Cannot insert the value NULL into column ‘name’, table ‘database_name.dbo.Users’; column does not allow nulls. INSERT fails.

I am following this tutorial.

<%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" 
AutoEventWireup="true" CodeBehind="test.aspx.cs" 
Inherits="Spravochnik.Users.test" %>

<asp:Content ContentPlaceHolderID="BodyPlaceHolder" runat="server">

<script runat="server">
    private void store(object source, EventArgs e) {
        SqlDataSource1.Insert();
    }
</script>

<asp:SqlDataSource 
    ID="SqlDataSource1" 
    runat="server" 
    DataSourceMode="DataReader" 
    ConnectionString="Data Source=DESKTOP-FJR7LSU;Initial Catalog=spravochnik;Integrated Security=True"
    SelectCommand="SELECT * FROM Users"
    InsertCommand="INSERT INTO Users (name, surname) VALUES (@Name, @Surname)">
        <InsertParameters>
            <asp:FormParameter Name="Name" FormField="NameBox" />
            <asp:FormParameter Name="Surname" FormField="SurnameBox" />
        </InsertParameters>
</asp:SqlDataSource>

<asp:TextBox ID="NameBox" runat="server" />
<asp:RequiredFieldValidator
    ID="RequiredFieldValidator1"
    runat="server"
    ControlToValidate="NameBox"
    Display="Static"
    ErrorMessage="Please Enter User's Name." /><br />

<asp:TextBox ID="SurnameBox" runat="server" />
<asp:RequiredFieldValidator
    ID="RequiredFieldValidator2"
    runat="server"
    ControlToValidate="SurnameBox"
    Display="Static"
    ErrorMessage="Please Enter User's Surname." /><br />

<asp:Button ID="Button" runat="server" Text="Add" OnClick="store" />


</asp:Content>

Site.Master

<%@ Master Language="C#" AutoEventWireup="true" 
CodeBehind="Site.master.cs" Inherits="Spravochnik.Site" %>

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<link href="~/Public/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<link href="~/Public/css/stylesheet.css" rel="stylesheet" type="text/css" />
<asp:ContentPlaceHolder ID="head" runat="server" />
</head>
<body>
<form runat="server">
    <div class="container">
        <div style="padding-top:50px">
            <asp:ScriptManager runat="server">
                <Scripts>
                    <asp:ScriptReference Path="~/Public/js/jquery.js" />
                    <asp:ScriptReference Path="~/Public/js/bootstrap.min.js" />
                </Scripts>
            </asp:ScriptManager>
            <asp:ContentPlaceHolder ID="BodyPlaceHolder" runat="server" />
        </div>
    </div>
</form>
</body>
</html>

Please help, Thanks in advance!


Solution

  • Don't know why but when I merge Master and child pages to a single one, it works fine. Thanks for your help!