0

I have two listboxes whose values are sent into a TableC via a button.

<asp:SqlDataSource ID="sql1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionDataBase %>" 
        SelectCommand="SELECT [Name] + ' (' + [CNbr] + ')' AS FullName, [CNbr] AS CNum FROM [TableA] ORDER BY [Name]">
    </asp:SqlDataSource>

    <asp:ListBox ID="lst1" runat="server" DataSourceID="sql1" DataTextField="FullName" DataValueField="CNum" AutoPostBack="true">
    </asp:ListBox>

    <asp:SqlDataSource ID="sql2" runat="server" 
                ConnectionString="<%$ ConnectionStrings:ConnectionDataBase %>"  
                InsertCommand="INSERT INTO [TableB] ([CNbr], [RDate]) VALUES (@CNbr, @RDate)" 
        <InsertParameters>
            <asp:Parameter Name="CNbr" Type="String" />
            <asp:Parameter Name="RDate" Type="DateTime" />
        </InsertParameters>

        <asp:ImageButton ID="ibnCheckOutBtn" runat="server" 
            ImageUrl="./images/vidCheckOutButton.png" onclick="ibnCheckOutBtn_Click"   />   

ASPX.CS file:

protected void ibnBtn_Click(object sender, ImageClickEventArgs e)
{
    sql2.Insert();
}

I don't really know C# and my class doesn't cover most C#, so I am looking for a solution that doesn't use a lot of behind-code. The error I get is:

Cannot insert the value NULL into column 'CNbr', table 'TableB'; column does not allow nulls. INSERT fails. The statement has been terminated.

However, nulls should not occur because the values are taken from a fully populated listbox. Help?

2
  • The variable has to have the same name. Either use CNbr or cnum, but not both. [CNbr] AS CNum Commented Apr 8, 2013 at 21:32
  • Where did all the other posts go? Commented Apr 9, 2013 at 2:31

1 Answer 1

1

You will need to assign the values to sql2 insert parameters in a similar way as follows:

protected void ibnBtn_Click(object sender, ImageClickEventArgs e)
{
    sql2.InsertParameters["CNbr"].DefaultValue = this.FindControl("lst1").SelectedValue;
    sql2.InsertParameters["RDate"].DefaultValue = DateTime.Now.ToString();
    sql2.Insert();
}
Sign up to request clarification or add additional context in comments.

2 Comments

Hey,I get a red squiggly line under .SelectedValue; , and I don't know what is it's cause.
change this.FindControl("lst1").SelectedValue; to ((ListBox)this.FindControl("lst1")).SelectedValue;. I forgot the cast. Depending on your aspx page structure, you might also need to adjust how you 'find' the listbox if FindControl does not work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.