Search code examples
asp.net.netsqldatasource

SqlDataSource Insert code behind variable


I have the following SqlDataSource

<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
        ConnectionString="<%$ ConnectionStrings:orangefreshConnectionString1 %>" 
        InsertCommand="INSERT INTO [Chat] ([Username], [Message]) VALUES (@Username, @Message)" 
        SelectCommand="SELECT [Id], [Username], [Message], [Date] FROM [Chat] ORDER BY [Id]" >
        <InsertParameters>
            <asp:Parameter Name="Message" Type="String" />
            <asp:Parameter Name="Date" Type="DateTime" /> 
            <asp:Parameter Name="Username" Type="String" />
        </InsertParameters>
    </asp:SqlDataSource>

Which controls the following FormView:

<asp:FormView ID="FormView1" runat="server" DefaultMode="Insert"
        OnItemInserted="fv_ItemInserted" RenderOuterTable="False" 
            DataSourceID="SqlDataSource1">
        <InsertItemTemplate>
            <asp:Panel ID="Panel1" runat="server" DefaultButton="Button1">
            <asp:TextBox ID="TextBox1" runat="server" CssClass="chattxtbox"
            Text='<%# Bind("Message") %>' autocomplete="off"></asp:TextBox>
        <asp:Button ID="Button1" runat="server" CommandName="insert" style="display:none" Text="Button" OnClick="insertUser"/>
            </asp:Panel>
        </InsertItemTemplate>
        </asp:FormView>

I want to be able a variable's content into the Username column, so on Button1 I set the following event: OnClick="insertUser"

 protected void insertUser(object sender, EventArgs e)
    {
        string username1 = User.Identity.Name;
        SqlDataSource1.InsertParameters.Add("Username", username1);
        SqlDataSource1.Insert();
    }

This isn't working though, I don't get any SQL error message at all, is this the right way to do this? And where did I go wrong?


Solution

  • Change Insert Parameter to SessionParameter.

    <InsertParameters>
       <asp:Parameter Name="Message" Type="String" />
       <asp:Parameter Name="Date" Type="DateTime" /> 
       <asp:Parameter Name="Username" Type="String" />
       <asp:SessionParameter Name="Username" SessionField="Username" Type="String" />
    </InsertParameters>
    

    And in Page_Load handler,

    Session["Username"]=User.Identity.Name;